JAVASCRIPT
Access Previous State or Prop Values in React
Develop a custom React hook to store and retrieve the previous value of any state or prop, useful for comparing current and past data in effects or logic.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
// The ref object is a generic container whose current property is mutable
// and can hold any value, similar to an instance field on a class
const ref = useRef();
// Store current value in ref on *every* render
// before the component renders again for the *next* render
useEffect(() => {
ref.current = value;
});
// Return previous value (happens before the useEffect above updates it)
return ref.current;
}
How it works: The `usePrevious` hook allows you to get the previous value of a prop or state. It works by storing the `value` passed to it in a `useRef` hook during each render. In the next render cycle, `ref.current` will hold the value from the *previous* render, while the `useEffect` callback (which runs after render) will update `ref.current` with the *current* value for the *next* cycle. This is invaluable for logic that requires comparing current and past states, such as conditional updates.