JAVASCRIPT
Get the Previous Value of a State or Prop
A custom React hook to efficiently track and return the previous value of any state or prop, ideal for comparing current and past values in useEffect.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
// Example Usage:
// function Counter() {
// const [count, setCount] = useState(0);
// const prevCount = usePrevious(count);
//
// return (
// <div>
// <h1>Current: {count}, Previous: {prevCount}</h1>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// </div>
// );
// }
How it works: This `usePrevious` hook utilizes `useRef` to store a mutable value that persists across renders without causing re-renders itself. Inside a `useEffect` hook, it updates `ref.current` to the latest `value` after every render. By returning `ref.current`, it provides access to the value from the *previous* render cycle, enabling easy comparisons, for instance, in other `useEffect` dependencies.