JAVASCRIPT

usePrevious to access a component's previous state or props

A concise React hook that provides access to the previous value of a state or prop, enabling comparison and side effects based on changes.

import { useRef, useEffect } => 'react';

  function usePrevious(value) {
    const ref = useRef();

    useEffect(() => {
      ref.current = value; // Store current value in ref after render
    }, [value]); // Only re-run if value changes

    return ref.current; // Return the stored previous value
  }

  // 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 provides a way to access the value of a state or prop from the previous render cycle. It uses a `useRef` to store the current value after each render, ensuring that on the next render, `ref.current` holds the value from the *previous* render. This is particularly useful when you need to compare a current value with its previous counterpart to trigger side effects, such as animating a change or conditionally fetching data based on a prop's alteration.

Need help integrating this into your project?

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

Hire DigitalCodeLabs