Categories
React Answers

How to compare objects with React useEffect hook?

Spread the love

Sometimes, we want to compare objects with React useEffect hook.

In this article, we’ll look at how to compare objects with React useEffect hook.

How to compare objects with React useEffect hook?

To compare objects with React useEffect hook, we can create a hook that keeps the previous value of a state.

For instance, we write

const usePrevious = (value) => {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

const useExample = (apiOptions) => {
  const myPreviousState = usePrevious(apiOptions);
  const [data, updateData] = useState([]);
  useEffect(() => {
    if (myPreviousState && !_.isEqual(myPreviousState, apiOptions)) {
      updateData(apiOptions);
    }
  }, [apiOptions]);
};

to create the usePrevious hook that keeps the value state’s value in a ref.

value is updated on every render since we call useEffect with no 2nd argument.

And then we return the ref’s value.

Then we use the usePrevious hook in the useExample hook.

In it, we call useEffect to run the callback when apiOptions changes.

We get the previous value of apiOptions with the usePrevious hook.

Then we check if the myPreviousState value is the same as apiOptions with the Lodash isEqual method.

Conclusion

To compare objects with React useEffect hook, we can create a hook that keeps the previous value of a state.

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 *