JAVASCRIPT

Custom usePrevious Hook to Track Previous State

Create a `usePrevious` custom React hook to easily access the previous value of a prop or state variable within your functional components.

import { useRef, useEffect } 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}</p>
//       <p>Previous: {prevCount}</p>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The `usePrevious` hook provides a way to get the value of a state or prop from the previous render cycle. It leverages `useRef` to store the value between renders without causing re-renders itself. Inside a `useEffect` hook, the `ref.current` is updated with the current `value` after the render, ensuring that on the next render, `ref.current` holds the value from the *previous* render.

Need help integrating this into your project?

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

Hire DigitalCodeLabs