← Back to all snippets
JAVASCRIPT

Track Previous State or Prop Values with React's `usePrevious` Hook

Create a `usePrevious` custom hook to easily access the prior value of any state or prop, useful for comparing current and historical data in your React components.

import { useRef, useEffect } => 'react';

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

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

  return ref.current;
}

// Example Usage:
// 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 provides a simple way to store and retrieve the value of a state or prop from the previous render cycle. It leverages `useRef` to create a mutable `ref` object that persists across renders. Inside a `useEffect` hook (which runs after every render), the `ref.current` is updated with the current `value`. Before this update, `ref.current` still holds the value from the *previous* render, which is then returned by the hook. This is useful for comparing current values with their immediate predecessors, such as detecting changes in props or state for conditional logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs