← Back to all snippets
JAVASCRIPT

Creating a usePrevious Hook to Track Previous State or Prop Values

Build a reusable React custom hook, usePrevious, to easily access the previous value of any state or prop, useful for comparing changes across renders.

import React, { useRef, useEffect } from 'react';

// Custom hook to get the previous value of a prop or state
function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value; // Store current value in ref after render
  }, [value]); // Rerun only if value changes
  return ref.current; // Return the previous value (before this render)
}

function Counter() {
  const [count, setCount] = React.useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
      <p>Current Count: {count}</p>
      <p>Previous Count: {prevCount !== undefined ? prevCount : 'N/A'}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

export default Counter;
How it works: The `usePrevious` custom hook provides a way to access the value of a state or prop from the *previous* render cycle. It leverages `useRef` to store the current value (which becomes the "previous" value in the next render) and `useEffect` to update this reference *after* the component has rendered. This hook is incredibly useful for comparing current and previous values, which is a common requirement in many React components for triggering side effects or conditional rendering based on value changes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs