Categories
React

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

Spread the love

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.

Now in App , we create the count state which we want to get the previous value of.

Then we call our usePrevious hook with count to get the previous value of count .

And we watch the value with the useEffect hook to log the prevCount and count .

And we watch the values by passing prevCount and count in the 2nd argument.

Below that, we add the button with the onClick prop set to a function that calls setCount to increment the count.

And we show the count below that.

The useEffect callback should log the prevCount and count values where prevCount should be the previous value of count .

Conclusion

We can watch the previous value of a state by creating our own hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *