Let's go! Hey, guys, welcome. Welcome to how not to use UseEffect. Oh, UseEffect is a little bit naughty, so we are going to take a look at it and see how we can use it in the right way and the things that we shouldn't do.
So, as you know, my name is Mohamed, I am Senior Software Frontend Engineer at IO. I'm here because I'm starving for React and JavaScript, so let's get on to it.
So, our journey. Our journey starts with a little bit of history, and then we will answer three questions. What, why, and when. These are critical questions for UseEffect, because based on these questions, we are going to consider some situations and some solutions for those situations. So this is tricky, keep in mind.
So, history. In around 2019, React 16.8, they introduced Hooks Hooks evaluation. So the thing is, UseEffect Hook introduced at that time. Actually, since we were migrating to Hooks in Hooks Flingy, so it was somehow a replacement for component dismount and also component update in class components. So at the end of the day, effectively, much cleaner code in Hook components.
So, first of all, what is it? As you know, UseEffect is just a hook. It has two parameters, a callback and dependency. It is better to rename callback to setup because it is somehow a setup for your effect. Actually, UseEffect is like a Swiss Army knife, so you should be careful. So, a hook that runs under conditions. So under some conditions that we are going to learn, it runs your callback once the React mounts the component, once. As soon as it detects some changes in dependencies, makes sense, we have a dependency array there, so as soon as one of them has changed, and the other one is on each render. These are three situations that a hook, a React actually is going to call your callback. They use effect hook.
So, the thing about useEffect is, why do we have it? Actually, yeah, because it lets you perform some side effects, for instance, fetching data, timers, JavaScript stuff and more. So let's consider the first useEffect callback called by React. The first one is, as soon as React mounts the component once, I guess everybody is familiar with that. So if you pass the second parameter, an empty array, so it's going to run your callback once, and whenever the component mounts to the DOM. So the thing is, in this case we are fetching some articles. Yeah, makes sense.
Comments