JAVASCRIPT

Get Previous State or Prop Value with `usePrevious`

Create a concise custom React hook to easily access the previous value of any state or prop, useful for comparing changes or triggering effects.

import { useRef, useEffect } from 'react';

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

  useEffect(() => {
    ref.current = value; // Update the ref's current value *after* render
  });

  return ref.current; // Return the *previous* value
}

// Example usage:
/*
function Counter() {
  const [count, setCount] = 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>
    </div>
  );
}
*/
How it works: The `usePrevious` hook provides a simple way to store and retrieve the value of a state or prop from the component's previous render cycle. It uses a `useRef` to persist the value across renders and an `useEffect` hook to update this `ref` *after* the component has rendered. This allows you to compare the current value with its previous state, which is useful for conditional logic or debugging.

Need help integrating this into your project?

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

Hire DigitalCodeLabs