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;
});
Pros
Excluding from dependency array: When you want to refer a latest value or callback function in the
useEffectorcustom hook, you can fetch them safely withoutdependency array.Prevent unnecessary rendering: The
useRefdoesn't trigger unnecessary rendering, therfore it optimizes performance.
Top comments (0)