The Latest Ref Pattern lets you access the newest state/props inside a stable function without adding them to a
useEffectdependency list.
Hooks capture values at the time a function is created. If a callback doesn’t update when state/props change → it may use old values.
const feedPet = useCallback(async () => {pet.eat(selectedPetFood)}, []) // stale closure
Store the latest values in refs and read from them inside stable functions.
const petRef = useRef(pet)const foodRef = useRef(selectedPetFood)useEffect(() => {petRef.current = petfoodRef.current = selectedPetFood}, [pet, selectedPetFood])const feedPet = async () => {petRef.current.eat(foodRef.current)}
Now feedPet is stable but always uses fresh values.
Use it when you need:
function useDebounce(callback, delay) {const ref = useRef(callback)useEffect(() => {ref.current = callback}, [callback])return useMemo(() => debounce(() => ref.current(), delay),[delay])}
Now the debounced function stays stable but always runs the latest callback.