JAVASCRIPT
Accessing Previous State or Prop Values with usePrevious
Track and compare the previous value of any state or prop in your React components using the `usePrevious` custom hook, essential for specific lifecycle logic.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
return ref.current;
}
How it works: The `usePrevious` hook provides a simple way to access the value of a prop or state from the previous render cycle. It uses `useRef` to store the current value after each render, making the 'previous' value available on the subsequent render. This is particularly useful for comparing current and old values to trigger specific side effects.