React usePrevious hook

React, Hooks, State, Effect · Nov 16, 2020

Stores the previous state or props.

  • Create a custom hook that takes a value.
  • Use the useRef() hook to create a ref for the value.
  • Use the useEffect() hook to remember the latest value.
const usePrevious = value => {
  const ref = React.useRef();
  React.useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};
const Counter = () => {
  const [value, setValue] = React.useState(0);
  const lastValue = usePrevious(value);

  return (
    <div>
      <p>
        Current: {value} - Previous: {lastValue}
      </p>
      <button onClick={() => setValue(value + 1)}>Increment</button>
    </div>
  );
};

ReactDOM.render(<Counter />, document.getElementById('root'));

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • React useMediaQuery hook

    Checks if the current environment matches a given media query and returns the appropriate value.

    React, Hooks · Oct 13, 2021

  • React useSearchParam hook

    Tracks the browser's location search param.

    React, Hooks · Oct 13, 2021

  • React useHash hook

    Tracks the browser's location hash value, and allows changing it.

    React, Hooks · Oct 2, 2021