Codementor Events

useEffectX: A better alternative to useEffect

Published Aug 18, 2020
useEffectX: A better alternative to useEffect

Image by Avery Morrow

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?

Solution 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 ?

Can we have something similar to componentDidUpdate ? We can have previous and current values of the dependencies as the argument of the callback of useEffect.

That could save us a lot of time while working with update scenarios in useEffect hook.

Solution 2

I was able to package everything in a npm package, which can act as a drop in replacement for useEffect anywhere. I call it useEffectX. Let’s see the the same example we showed in above codesandbox with our shiny new useEffectX.

Notice now , how we have access to previous values in the arguments of useEffectX’s callback itself. We don’t need any usePrevious hook now plus the arguments are completely optional same with any function. The code snippets below will also work exactly same as official useEffect

useEffectX(() => {
  console.log(val, someotherVal)
}, [val, someotherVal])

useEffectX(() => {
 console.log("do something after every render")
})

Thanks. Please let me know , what you all think about this useEffectX.

https://twitter.com/simbatheesailor

Discover and read more posts from anil chaudhary
get started
post commentsBe the first to share your opinion
Show more replies