JAVASCRIPT

Track Previous State or Prop Values with usePrevious

Implement a custom `usePrevious` hook in React to easily access the previous value of a state variable or prop within your components.

import { useEffect, useRef } from 'react';

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

  useEffect(() => {
    ref.current = value; // Store current value in ref 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 !== undefined ? prevCount : 'N/A'}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
*/
How it works: The `usePrevious` hook provides a simple way to access the value of a state variable or prop from the previous render cycle. It leverages `useRef` to store the value after each render, but returns the value from the *previous* render. This is particularly useful for comparing current and past values within `useEffect` hooks, enabling conditional logic based on changes or for animations that depend on a previous state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs