JAVASCRIPT
Access Previous State or Prop Values with usePrevious Hook
The `usePrevious` custom React hook provides a simple way to store and retrieve the previous value of any given state or prop, useful for change detection.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
How it works: This hook provides a straightforward method to access the previous value of a state variable or prop. It utilizes a `useRef` to persistently store the value. After each render, the `useEffect` hook updates `ref.current` with the `value` from the *current* render cycle. Consequently, on subsequent renders, `ref.current` will contain the `value` from the *previous* render, enabling easy comparison between the current and prior values.