How to get and compare the previous state using useEffect Hooks

React JS creators develop React hooks to simplify functional components. So now functional components can also hold their own state using hooks. It’s like hooks added flesh in the skeleton. In this article, we will see how to get and compare the previous state using useEffect hook with React Hooks.

if you know class components life cycle methods then this article could go very simple to understand. So as we know useEffect is also a lifecycle method but we use this method in functional components with hooks. Simply useEffect can also be called a hook.

useEffect is a combination of 3 class component lifecycle methods, which are componentDidMount, componentDidUpdatea and componentWillUnmount.

Now let’s talk about our main topic. So as we know now useEffect also get fired once modify your state. That means we will get always the updated state value in uesEffect method ( just like in componentDidUpdate). Now the question arises, how we will compare the previous state with the new state if I am receiving the new and updated value.

So as I mentioned we do get the new value always in useEffect so what we can do we can store our old value. As far we know we receive previous props and previous state in the componetDidUpdate lifecycle method of the class component. Which is not the same in the useEffect that’s we will store our previous value manually.

Now to accomplish our goal react have already created something for us that we can use here. So we will use a hook that will store previous value for us every time we update our state. The hook for this purpose we will use is useRef hooks. Yes, that is right.

Let’s see an example to make it more clear, In this example, I will store the old values in the useRef hook so that next we will able to compare that. It is pretty simple though.

import React, { useEffect, useRef, useState } from "react";
const App = () => {
  const [user, setUser] = useState("John");
  const prevUser = useRef();

  useEffect(() => {
    if (user !== prevUser.current) {
      prevUser.current = user;
    } else {
      // do something when matches both name
    }
  }, [user]);
  return (
    <>
      <div>
        new value {user} old value {prevUser.current}
      </div>
      <button onClick={() => setUser("aaafd")}>Click me </button>
    </>
  );
};
export default App;

So as you can see we will have old value and new value respectively if we pass new value always to setUser.

So that’s all about how to get and compare the previous state using the useEffect hook with React Hooks. I hope this article has helped you.

If you have any queries or something please leave the comment in the comments section below.

see also

Leave a Reply

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