Skip to Content
ohooks

useLatest

Returns a ref object whose .current property is synchronously updated to the latest value after every render.

Loading preview...

The useLatest hook stores any value in a RefObject and keeps .current synchronized via useIsomorphicLayoutEffect so asynchronous callbacks, timers, and subscriptions can read the freshest value without stale closures.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useLatest.json

Usage

Examples

Reading Fresh State Inside a Long-Lived Timer

Read countRef.current inside an interval or timeout so you do not need to recreate the timer every time count changes.

Wrapping Event Handlers for External Subscriptions

Store a prop callback in useLatest so an external library or WebSocket listener only subscribes once.