useLatest
Returns a ref that always points at the latest value.
Returns a ref that always points at the latest value.
Import
import { useLatest } from '@kamod-ch/hooks'Live demo
Basic demo
Returns a ref that always points at the latest value.
latest.current: initial
import { useState } from 'preact/hooks'
import { useLatest } from '@kamod-ch/hooks'
export default function UseLatestDemo() {
const [value, setValue] = useState('initial')
const latest = useLatest(value)
return (
<div>
<input value={value} onInput={(event) => setValue(event.currentTarget.value)} />
<p><strong>latest.current:</strong> {latest.current}</p>
</div>
)
}
API
TypeScript signature
declare function useLatest<T>(value: T): import("preact/hooks").MutableRef<T>;
export default useLatest;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.