usePrevious

Accessing the previous value of a state is a relatively common use case. You can achieve this with a custom hook and a ref:


RESETRUNFULL
function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return <h1>Now: {count}, before: {prevCount}</h1>;}function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;}

This would work for props, state, or any other calculated value.