JAVASCRIPT

Access Previous State or Prop with `usePrevious` Hook

Develop a `usePrevious` React hook to easily access the previous value of any prop or state variable, useful for tracking changes and conditional logic.

import { useEffect, useRef } from 'react';

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

  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref.current;
}
How it works: The `usePrevious` hook provides a simple way to access the value of a prop or state variable from the previous render cycle. It leverages `useRef` to create a mutable object that persists across renders. Inside a `useEffect` hook, the `ref.current` is updated with the current `value` *after* the render has committed to the DOM. When the hook is called in the next render, `ref.current` will still hold the value from the *previous* render, allowing you to compare current and previous values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs