Skip to content

useLatest

Category
Export Size
105 B
Last Changed
5 days ago

Returns a ref whose .current always holds the latest rendered value.

Demo

Usage

tsx
import { 
useLatest
} from '@reause/shared'
const
latest
=
useLatest
(value)
// the ref object itself is returned — not a `[ref]` tuple // `latest.current` is always the value of the latest render

The ref object identity is stable for the lifetime of the component, so an async callback captured on an earlier render (a setTimeout, a promise continuation, a subscription handler) reads the freshest value when it finally runs — no dependency array or re-subscription needed:

tsx
const 
latest
=
useLatest
(value)
// scheduled now, logs whatever `value` is when the timer fires
setTimeout
(() =>
console
.
log
(
latest
.
current
), 1000)

Type Declarations

ts
export function useLatest<T>(value: T): {
    readonly current: T;
}

Source

Source · Demo · react-use

Contributors

hairyf

Changelog

v0.1.6 on
e4726 - feat(shared): add useLatest (#916)

Released under the MIT License. v0.1.8