JAVASCRIPT

React Hook: usePrevious for Tracking Value History

The `usePrevious` custom React hook provides a way to access the previous value of a state or prop, which is invaluable for comparing current and past states.

import { useRef, useEffect } from 'react';

function usePrevious(value) {
  const ref = useRef();

  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref.current;
}

// How to use it:
/*
function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCount !== undefined ? prevCount : 'N/A'}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}
*/
How it works: The `usePrevious` hook utilizes `useRef` to store the value from the previous render. Inside a `useEffect`, the `ref.current` is updated with the *current* `value` after the render has committed to the DOM. Crucially, `useRef` does not trigger re-renders when its `.current` property changes, and its value persists across renders, making it perfect for holding the previous value to be returned on the *next* render.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs