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:

function App() {
	  const [varA, setVarA] = useState(0);
	  const [varB, setVarB] = useState(0);
	  // Don't do this!
	  useEffect(() => {
	    const timeoutA = setTimeout(() => setVarA(varA + 1), 1000);
	    const timeoutB = setTimeout(() => setVarB(varB + 2), 2000);

	    return () => {
	      clearTimeout(timeoutA);
	      clearTimeout(timeoutB);
	    };
	  }, [varA, varB]);

	  return (
	    <span>
	      Var A: {varA}, Var B: {varB}
	    </span>
	  );
	}
view raw
badCodePart1.js hosted with ❤ by GitHub

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 functions with more code and variables I guarantee you will miss this. So do the right thing and split your useEffect.

#react-hook #web-development #react #useeffect #hooks-state

useEffect: 4 Tips Every Developer Should Know
3.50 GEEK