Created
February 9, 2023 07:06
-
-
Save artalar/4a76dfc7abb8cea8b0ef58ff86ecd6e4 to your computer and use it in GitHub Desktop.
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
// https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback | |
// https://github.com/reactjs/rfcs/pull/220#issuecomment-1259938816 | |
import React from 'react'; | |
// Allow to access a fresh closures in the function but returns stable reference during rerenders | |
export function useCallbackRef<T extends (...args: unknown[]) => unknown>(callback: T): T { | |
const ref: React.MutableRefObject<{ | |
stableFn: T; | |
callback: T; | |
}> = React.useRef({ | |
stableFn: ((...args) => ref.current.callback(...args)) as T, | |
callback, | |
}); | |
// useLayoutEffect for React <18 | |
React.useLayoutEffect(() => { | |
ref.current.callback = callback; | |
}); | |
return ref.current.stableFn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What does this comment mean? What should I use with React 18+ here?