My experience with React hooks have been amazing. In this article, I will precisely talk on one of the most prominent hooks that we use on a daily basis which is useEffect.

I am assuming the readers coming to this article has good understanding on useEffect. If not, please first go through the concept at reactjs.org.

So essentially, useEffect react to changes in dependency list. They have replaced **_componentDidMount, componentDidUpdate, componentWillUnmount and componentWillReceiveProps in _**class based react components.

It’s very common to react to changes in props values or state values over the lifetime of a component. we also need to compare previous values and current values when reacting to changes often. In the class based component, we had componentDidUpdate for the similar use-cases.

It has following interface:

componentDidUpdate(prevProps, prevState, snapshot)

You have access to prevProps(previous props) and**_ prevState(previous state)_**, which can be used to make comparisons and react appropriately.

What about useEffect, how would you do those kind of comparison with them?

S

olution 1

You can have a usePrevious custom hook which will always give you the previous value and that you make use in your useEffect to complete the comparison. Let’s see some code.

Notice, how usePrevious hook helps us by keeping a track of previous value. Now think about scenario, when there are more than one dependency in our useEffect. We need to make use of **_usePrevious _**hook that many times or we have to re-define our usePrevious hook to track an array of dependency.

Isn’t it too much of work every time ?

#react #react-hook #react-native #javascript #reactjs

A better alternative to useEffect
26.00 GEEK