Skip to content

Instantly share code, notes, and snippets.

@mdjastrzebski
Created August 14, 2025 13:11
Show Gist options
  • Select an option

  • Save mdjastrzebski/ed5ad76de860c84eb9dd12e5aeeb7879 to your computer and use it in GitHub Desktop.

Select an option

Save mdjastrzebski/ed5ad76de860c84eb9dd12e5aeeb7879 to your computer and use it in GitHub Desktop.
use-latest-prop-value
/**
* Returns the latest value of given prop as a ref.
*
* This function allows treating given prop as a non-reactive value, that should be
* accessible in `useEffect` but does not trigger effect re-run.
*
* @param value - The prop value to be used as a ref
* @returns A ref that will always hold the latest value of the prop
*/
function useLatestPropRef<T>(value: T) {
const ref = React.useRef(value);
// Execute before useLayoutEffect and useEffect
React.useInsertionEffect(() => {
ref.current = value;
});
return ref;
}
export function Modal({ open, onModalShow, onUnmount }: ModalProps) {
const onModalShowRef = useLatestPropRef(onModalShow);
const onUnmountRef = useLatestPropRef(onUnmount);
React.useEffect(() => {
if (open) {
animateOpen(onModalShowRef.current); // Access the latest prop value
}
// Rules of Hooks is happy
}, [open]);
React.useEffect(() => {
return () => {
onUnmountRef.current?.();
};
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment