React useEffect: 4 Tips Every Developer Should Know
Let’s talk about useEffects in React Hooks! I’m going to share with you 4 tips you should have in mind when using useEffect.
Use a useEffect for a single purpose
In React Hooks, you can have multiple useEffect functions. This is a great feature because, if we analyze how to write clean code, you’ll see that functions should serve a single purpose (much like how a sentence should communicate one idea only).
Splitting useEffects into short and sweet single-purpose functions also prevents unintended executions (when using the dependency array).
For example, let’s say you have varA that is unrelated to varB, and you want to build a recursive counter based on useEffect (with setTimeout) so let’s write some bad code:
As you can see, a single change in any of the variables varA and varB will trigger an update in both variables. This is why this hook doesn’t work properly.
Since this is a short example, you may feel that it’s obvious, however, in longer…