JAVASCRIPT

Track Previous Value of React State or Prop

Keep track of the previous value of any React state or prop using a simple `usePrevious` custom hook, enabling comparisons and conditional 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 allows you to get the value of a state or prop from the previous render. It uses a `useRef` to store the value, which persists across renders without causing re-renders itself. In the `useEffect` callback, the current `value` is stored in the ref *after* the render, making it available as the "previous" value in the subsequent render, useful for comparing state changes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs