Sometimes we want to compare the old and new value of a state change.

In this article, we’ll look at how to get th previous value of a state to the new one.

Create Our Own Hook

We can get the old value of a state with our own hook.

For instance, we can write:

import { useEffect, useRef, useState } from "react";

const usePrevious = (value) => {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};
export default function App() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  useEffect(() => {
    console.log(prevCount, count);
  }, [prevCount, count]);
  return (
    <div className="App">
      <button onClick={() => setCount((c) => c + 1)}>increment</button>
      <p>{count}</p>
    </div>
  );
}

We create the usePrevious hook with the value parameter which is state we want to get the previous value from,

In the hook, we create a ref with the useRef hook to create a non-reactive property.

Then we add the useEffect hook with a callback that sets the ref.current to value to set the previous value.

And we return ref.current which has the previous value.

#javascript #web-development #software-development #technology #programming

How to compare Old Values and New Values on React useEffect Hook?
4.45 GEEK