Last active
July 21, 2020 16:59
-
-
Save andymatuschak/c5f2b8b68821a95e5b339bfcd4bfcee1 to your computer and use it in GitHub Desktop.
late-bound React hook callbacks, avoiding subtree re-renders when event callback deps change
This file contains 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
function useWeakRef<T>(value: T): React.MutableRefObject<T> { | |
const ref = useRef(value); | |
useEffect(() => { | |
ref.current = value; | |
}, [value]); | |
return ref; | |
} | |
function useByrefCallback<Args extends unknown[], Result>( | |
callback: (...args: Args) => Result, | |
): (...args: Args) => Result { | |
const callbackRef = useWeakRef(callback); | |
return useCallback( | |
(...args: Args) => { | |
return callbackRef.current(...args); | |
}, | |
[callbackRef], | |
); | |
} | |
function MyComponent({handleFinish}: {handleFinish: () => void}) { | |
const handleFinish3 = useByrefCallback(() => { | |
analytics.finishLesson(/* etc */); | |
handleFinish(); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment