Why the heck did you effect?
With the addition of hooks to React 16.8, a new “lifecycle” handler entered our lives, the useEffect
hook.
This is hook (like its brother useLayoutEffect
) is responsible on all the side effects in the component lifecycle.
This includes state updates, property updates and so on.
useEffect
gives a functional component, the same abilities a class component has, when using the componentDidMount
, componentDidUpdate
and componentWillUnmount
lifecycle methods.
Here is a short example of replacing the class methods with a hook
useEffect(() => {}, []) // This will run only on component mountuseEffect(() => {}, [p1]) // This will run whenever 'p1' updatesuseEffect(() => {
return () => {}
}, []) // the returned method will run before the component unmounts
If you want to read more about the useEffect
hook, the React official docs are a good place to start.
Ok so far nothing interesting, so why do I even bother to write this post?
Because one of the things I find missing with the useEffect
hooks is the indication why did it run, or what exactly is the effect causing it to run.
That is why I’ve written my own useEffect
(with the not so sophisticated name useMyEffect
.You are welcome to suggest names in the comments).
So how does it work?
Here is the code:
The ‘App’ component is very simple. It has two state object (counter and now)
and one useEffect
listener. The difference is that I’m using my own useMyEffect
. This effect listener uses the useEffect
Original hook has its “engine” yet it has two small changes.
#1 It has a name property before the call back function. This enable us to know which effect ran when we have number of useEffect
in the same component.
#2 It receives its dependencies as an object and not as an array.
This gives it the ability to know why exactly did it ran and what dependency changed and made it run.
To see it in action, open this link https://1hpok.csb.app/ and look at the console, to see why did the effect run.
P.S:
off course you could do the same for useLayoutEffect
just replace the inner useEffect
with useLayoutEffect
.
And that’s it. I hope you liked this post and found it useful.