Home
React
Patterns: Latest Ref
Daniel Nguyen
Daniel Nguyen
July 23, 2025
1 min

The Latest Ref Pattern stores the latest callback or value in a ref, allowing a long-lived function to access current data without being recreated on every render.

1. Problem: Stale Closures

A callback can capture outdated values when it is created and then reused without updating its dependencies.

const feedPet = useCallback(() => {
pet.eat(selectedPetFood);
}, []); // Incorrect: captures initial values

Because the dependency array is empty, feedPet continues to reference the values captured by its original closure.

2. Solution: Store the Latest Values in Refs

const petRef = useRef(pet);
const foodRef = useRef(selectedPetFood);
useEffect(() => {
petRef.current = pet;
foodRef.current = selectedPetFood;
}, [pet, selectedPetFood]);
const feedPet = useCallback(() => {
petRef.current.eat(foodRef.current);
}, []);

Now feedPet has a stable identity and reads the latest values stored in the refs.

The refs update after each committed render where the dependencies change.

3. Real Use Case: Debounced Callbacks

A debounced function should retain its identity across renders while invoking the latest callback.

function useDebouncedCallback<T extends (...args: any[]) => void>(
callback: T,
delay: number
) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
const debounced = useMemo(
() =>
debounce((...args: Parameters<T>) => {
callbackRef.current(...args);
}, delay),
[delay]
);
useEffect(() => {
return () => debounced.cancel();
}, [debounced]);
return debounced;
}

This example assumes debounce is a utility that supports .cancel(), such as Lodash’s implementation.

  • The ref keeps the latest callback.
  • useMemo preserves the debounced function while delay remains unchanged.
  • Cleanup cancels pending invocations when the debounced function is replaced or the component unmounts.

Tags

#ReactPatterns

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

Advanced React Patterns
Patterns: Prop Collections and Getters
July 22, 2025
1 min
Dev98

Dev98

React · Next.js · Web development