Created
August 14, 2025 13:11
-
-
Save mdjastrzebski/ed5ad76de860c84eb9dd12e5aeeb7879 to your computer and use it in GitHub Desktop.
use-latest-prop-value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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