JAVASCRIPT

`usePrevious` Custom Hook to Get Previous Value

Discover how to create a `usePrevious` React hook for easily accessing the previous value of a prop or state variable within a functional component.

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;
}

// Example Usage:
/*
function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
*/
How it works: The `usePrevious` hook stores the *previous* value of a given state or prop. It utilizes a `useRef` to maintain a mutable reference that persists across renders without causing re-renders itself. Inside a `useEffect` hook, the `ref.current` is updated to the `value` *after* the render, meaning the value returned by `usePrevious` during the current render will always be the value from the *previous* render cycle.

Need help integrating this into your project?

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

Hire DigitalCodeLabs