JAVASCRIPT

Tracking Previous Prop or State with `usePrevious`

Create a custom React hook, `usePrevious`, to easily access the previous value of any prop or state variable, useful for comparing changes over renders.

import { useRef, useEffect } from 'react';

/**
 * Custom hook to get the previous value of a state or prop.
 * @param {any} value The current value to track.
 * @returns {any} The previous value.
 */
export function usePrevious(value) {
  // Create a ref to store the previous value
  const ref = useRef();

  // Use useEffect to update the ref after every render
  useEffect(() => {
    ref.current = value;
  }, [value]); // Only re-run if value changes

  // Return the previous value (which is stored in ref.current before the current render's update)
  return ref.current;
}

// 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` custom hook provides a way to access the value of a variable (like a prop or state) from the previous render. It leverages `useRef` to store the value across renders without triggering re-renders, and `useEffect` to update this stored value after the component has rendered. This is particularly useful for comparing current and past values to trigger specific side effects or behaviors.

Need help integrating this into your project?

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

Hire DigitalCodeLabs