React useEffect hook summary

useEffect besides useState is the most important React hook you have, so you need to understand it. Therefore, I again, want to make it clear at which point of time, which part of useEffect kicks in and executes. Next, I'll present some useEffect use cases. First example is for the case of a useEffect that runs when a state is updated or a key is pressed:

useEffect(() => { console.log('EFFECT RUNNING'); });

This changes when we add an empty array. So if we add an empty array, the function only executes for the first time this component was mounted and rendered, but not thereafter, not for any subsequent rerender cycle.

useEffect(() => { console.log('EFFECT RUNNING'); }, []);

Alternatively, we can add a dependency for the useEffect, like entered email or entered password if we have a login form in the page, for example. Now the function reruns whenever the component was re-evaluated and the dependency state was changed

useEffect(() => { console.log('EFFECT RUNNING'); }, [enteredPassword, enteredEmail]);

We also can have a cleanup function, which we can return. This cleanup function runs before the useEffect function runs, but not before the first time it runs.

useEffect(() => { console.log('EFFECT RUNNING'); return () => { console.log('EFFECT CLEANUP'); }; }, [enteredPassword])

Category: React Tags: #javascript, #react