JAVASCRIPT

Implementing a usePrevious Custom Hook in React

Learn to create a `usePrevious` React hook to easily access a prop or state's previous value, essential for comparing changes and implementing derived logic.

import { useRef, useEffect, useState } 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}, Previous: {prevCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
How it works: The `usePrevious` hook utilizes `useRef` to store the value from the previous render. In a `useEffect` hook, it updates the ref's current value *after* the render, ensuring `ref.current` always holds the value from the render *before* the current one. This is useful for comparing the current state/prop with its immediate past value.

Need help integrating this into your project?

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

Hire DigitalCodeLabs