JAVASCRIPT

Tracking Previous State or Props with usePrevious Hook

Create a `usePrevious` custom React hook to efficiently access the previous value of any state or prop, enabling powerful comparison and change detection logic within components.

import { useRef, useEffect } from 'react';

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

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

  return ref.current;
}

// How to use:
/*
import React, { useState } from 'react';
import usePrevious from './usePrevious'; // Assuming usePrevious.js

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 provides a way to access the value of a state or prop from the previous render cycle. It uses a `useRef` to store the value and updates it in a `useEffect` after every render. This is particularly useful for comparing current and previous values to trigger effects only when a specific change occurs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs