In this article, we will see how to compare oldValues and newValues using the React Hooks useEffect().

In some cases, we may need to perform certain actions only after the value in the state changes. In such a scenario, we have to compare whether the value in the state is changed or not before performing the action.

When we use useEffect(), we pass in a callback function that will be executed when the component mounts, updates, or unmounts. We can also pass in a second argument which is an array of dependencies. These dependencies determine when the callback function should be executed. There are two cases for this.

  1. If the array of dependencies is empty, the callback function is only executed when the component mounts.
  2. If the array contains one or more dependencies, the callback function is executed if any of those dependencies change. This is where we can compare old and new values.

Comparing the old and new values on useEffect()

In order to compare the old and new values of the state variables on useEffect(), we first, need to retain the old value of the variable. This can be done by using the useRef(). The new value can be passed as a dependency to the useEffect().

Following is the example of how to compare the old and new state values on useEffect()

import React, { useState, useEffect, useRef } from 'react';

function ExampleComponent(props) {
  const [count, setCount] = useState(0);

  const prevCountRef = useRef();

  useEffect(() => {
    prevCountRef.current = count;
  }, [count]);

  const prevCount = prevCountRef.current;

  return (
    <div>
      <p>Current count: {count}</p>
      {prevCount && <p>Previous count: {prevCount}</p>}
      <button onClick={() => setCount(count + 1)}>Increment count</button>
    </div>
  );
}

export default ExampleComponent;

Explanation:

In the above example, we have defined a functional component called ExampleComponent that uses the useState() hook to manage the state of a count variable. We have also defined a useRef() hook called prevCountRef to store the previous value of the count variable.

In the useEffect() hook, we update the prevCountRef.current value whenever the count variable changes. We then use the prevCount variable to display the previous value of the count variable.

This way we can compare the old and new state values of the count variable on useEffect() hook and perform certain actions only when the values change.

Categorized in:

Tagged in: