Skip to main content

useLatest

React state hook that returns the latest state as described in the React hooks FAQ.

This is mostly useful to get access to the latest value of some props or state inside an asynchronous callback, instead of that value at the time the callback was created from

Usage

Live Editor
function Demo() {
  const [count, setCount] = useState(0);
  const latestCount = useLatest(count);
  const handleAlertClick = () => {
    setTimeout(() => {
      alert(`Latest count value: ${latestCount.current}`);
    }, 3000);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
      <button onClick={handleAlertClick}>Show alert</button>
    </div>
  );
};

Result
Loading...

API

useLatest

Returns

React.MutableRefObject<T>: ref object

Arguments

ArgumentDescriptionTypeDefaultValue
valuetracked valueT (Required)-