How to know which dependency changed in useeffect

One way to know which dependency changed in useEffect is by comparing the previous value of the dependency with the current value. You can achieve this by using the useRef and useEffect hooks.

Here is an example:

In this example, we have a component called ExampleComponent that has a count state variable and a message state variable. We also have a useRef hook called prevCountRef, which is used to store the previous value of count.

In the useEffect hook, we compare the previous value of count (prevCountRef.current) with the current value of count. If they are different, we update the message state variable with the new count value.

By using this approach, you can easily identify which dependency has changed in useEffect and perform any necessary actions accordingly.

Leave a comment