Skip to content

Instantly share code, notes, and snippets.

@artalar
Created February 9, 2023 07:06
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artalar/4a76dfc7abb8cea8b0ef58ff86ecd6e4 to your computer and use it in GitHub Desktop.
Save artalar/4a76dfc7abb8cea8b0ef58ff86ecd6e4 to your computer and use it in GitHub Desktop.
// 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;
}
@dartess
Copy link

dartess commented Mar 6, 2023

useLayoutEffect for React <18

What does this comment mean? What should I use with React 18+ here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment