← Back to all snippets
JAVASCRIPT

Creating a Custom `usePrevious` Hook

Learn how to implement a custom React `usePrevious` hook to easily access the previous value of any prop or state in your components.

import { useRef, useEffect } from 'react';

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}

// Example Usage:
// function MyComponent({ count }) {
//   const prevCount = usePrevious(count);
//   return (
//     <div>
//       <p>Current: {count}</p>
//       <p>Previous: {prevCount}</p>
//     </div>
//   );
// }
How it works: This custom hook leverages `useRef` to store the previous value of a variable. `useEffect` updates the `ref.current` *after* the render, ensuring that `ref.current` always holds the value from the *previous* render cycle when the component is re-rendered with a new `value`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs