JAVASCRIPT
Track Previous React Prop or State with `usePrevious` Hook
Create a custom `usePrevious` React hook to easily access the prior value of a prop or state variable, useful for comparing changes 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>
// <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 allows you to easily retrieve the value a prop or state variable had on the previous render. It leverages `useRef` to store the value and `useEffect` to update it after each render, making it simple to compare current and past values within effects or other logic.