Skip to content

Instantly share code, notes, and snippets.

@andymatuschak
Last active July 21, 2020 16:59
Show Gist options
  • Save andymatuschak/c5f2b8b68821a95e5b339bfcd4bfcee1 to your computer and use it in GitHub Desktop.
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
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