useLatestRef
Return a ref object whose .current property always points to the latest value. It is typically used to read the latest value inside long-lived callbacks (timers, event listeners) to avoid stale closures.
API
function useLatestRef<T>(value: T): React.MutableRefObject<T>;
Notes
- The ref is written during render and does not trigger re-renders; use state for reactive values.
Example
The following example shows an interval that always reads the latest input value.
Enter value:
Interval snapshot: —
import { useState } from "react";
import { useInterval, useLatestRef } from "@lilib/hooks";
function Example() {
const [value, setValue] = useState("");
const [snapshot, setSnapshot] = useState("");
const valueRef = useLatestRef(value);
const [start, cancel] = useInterval(() => {
// The interval callback is bound once, but reads the latest value via the ref.
setSnapshot(valueRef.current);
}, 1000);
return (
<>
<p>
Enter value:{" "}
<input
value={value}
onChange={(event) => {
setValue(event.target.value);
}}
/>
</p>
<div>
<button onClick={start}>Start</button> <button onClick={cancel}>Cancel</button>
</div>
<div>Interval snapshot: {snapshot || "—"}</div>
</>
);
}
export default Example;