Categories
React

How to Compare Old Values and New Values with the React useEffect Hook?

Spread the love

Sometimes, we may want to compare the old and new values of a state in our React component created with React hooks.

In this article, we’ll look at how to compare the old and new values of a state with components created with React hooks.

Store Old Values in a Ref

We can store old values in a ref since assigning values to them won’t trigger a re-rendering of the component but the value will persist after each render cycle.

Therefore, we can write:

import React, { 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: ", prevCount, "count: ", count);
  }, [prevCount, count]);

  return (
    <div className="App">
      <button onClick={() => setCount((c) => c + 1)}>increment</button>
      <p>{count}</p>
    </div>
  );
}

to create the usePrevious hook to store the previous value of a state.

The hook takes the value parameter with the state or prop value we want to store.

We call useEffect with a callback to set the current property of the ref to store value in it.

We didn’t pass in a 2nd argument so the useEffect callback will run every render cycle.

And we return the value of ref.current so that we can assign it to a value in a component and use it.

In App , we create the count state with the useState hook.

And we call the usePrevious hook with count to store the previous value of count in the ref ,

Below that, we watch the values of prevCount and count with the useEffect hook by passing in an array with prevCount and count as the 2nd argument.

Then below that, we have a button that calls setCount when we click it to update count .

And then we show the count .

In the console log, we should see that prevCount should have the previous value of count .

Conclusion

We can store the old value of a state or prop by storing the value in a ref so we can use it in our component.

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 *