← Back to all snippets
JAVASCRIPT

Getting the Previous Value of State or Props with usePrevious Hook

Learn to create a custom React hook, `usePrevious`, to easily access the prior value of any state or prop, essential for comparisons and lifecycle logic.

import { useRef, useEffect } from 'react';

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

  useEffect(() => {
    ref.current = value;
  }, [value]); // Only re-run if value changes

  return ref.current;
}

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

  return (
    <div>
      <p>Current: {count}, Previous: {prevCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
*/
How it works: The `usePrevious` hook leverages `useRef` to store the value from the previous render. Inside a `useEffect` hook, the `ref.current` is updated *after* the component has rendered with the new `value`. This ensures that when the hook returns `ref.current`, it's always providing the value from the *previous* render cycle, making it ideal for comparing current and past states or props.

Need help integrating this into your project?

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

Hire DigitalCodeLabs