Skip to content

useLatest

useLatest<T>(value): RefObject<T>

Defined in: src/hooks/useLatest/useLatest.ts:25

Keep a ref synced to the latest value of value after each render.

Useful for reading “live” props/state inside event handlers, timers, or external store subscriptions without re-attaching the listener on every render. The ref is updated in useEffect so its value reflects the most recently committed render.

Type Parameters

T

T

Parameters

value

T

Returns

RefObject<T>

Example

const latestOnChange = useLatest(onChange);
useEffect(() => {
const handler = (e: Event) => latestOnChange.current(e);
target.addEventListener('change', handler);
return () => target.removeEventListener('change', handler);
}, [target]);