DEV Community

Cover image for React.js ~The Latest Ref Pattern~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~The Latest Ref Pattern~

The Latest Ref Pattern is a simple design pattern that holds latest value or callback function without re-rendering.

Here is a basic implementation bellow:

const latestValueRef = React.useRef(value);
React.useLayoutEffect(() => {
  latestValueRef.current = value;
});
Enter fullscreen mode Exit fullscreen mode

Pros

  • Excluding from dependency array: When you want to refer a latest value or callback function in the useEffect or custom hook, you can fetch them safely without dependency array.

  • Prevent unnecessary rendering: The useRef doesn't trigger unnecessary rendering, therfore it optimizes performance.

Top comments (0)