Skip to content

Instantly share code, notes, and snippets.

@vzaidman
Last active January 31, 2020 11:38
Show Gist options
  • Save vzaidman/2996cfd9f0ff9ad50dbcefcad2f2fb3c to your computer and use it in GitHub Desktop.
Save vzaidman/2996cfd9f0ff9ad50dbcefcad2f2fb3c to your computer and use it in GitHub Desktop.
Advanced React- useCallback() Invalidates Too Often in Practice #14099
/*
Notice: This hook would be problematic in concurrent mode:
https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
*/
function useEventCallback(fn, dependencies) {
const ref = React.useRef(() => {
throw new Error('Cannot call an event handler while rendering.');
});
React.useEffect(() => {
ref.current = fn;
}, [fn, ...dependencies]);
return React.useCallback((...args) => (0, ref.current)(...args), []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment