← Back to all snippets
JAVASCRIPT

Storing Previous State or Prop Values with `usePrevious`

Learn how to create a custom `usePrevious` React hook to easily access the prior value of any state or prop, essential for comparing changes in components.

import { useRef, useEffect } from 'react';

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value; // Assign the current value to ref.current after render
  }, [value]); // Only re-run if value changes
  return ref.current; // Return the previous value (before current render)
}

// Example Usage:
/*
function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
*/
How it works: The `usePrevious` hook uses a `useRef` to store the value from the previous render. In the `useEffect` callback, which runs after every render, `ref.current` is updated to the `value` passed into the hook. However, when `usePrevious(value)` is called during the *current* render, `ref.current` still holds the value from the *previous* render, allowing you to access it for comparisons or other logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs