A mistake lots of React developers make almost everyday when using hooks.
lets take a look at the following UseEffect

const [count, setCount] = useState(0);

const [mouseClickCount, setMouseClickCount] = useState(0); useEffect(() => { if(mouseClickCount === 2 && count !== 0) {

setCount(count + 1 );

} else if(mouseClickCount === 1 && count === 0) {

setCount(count + 1 );

} }, [count, mouseClickCount]);

...

Do you see the problem here ?

well you guessed it, every single time this useEffect changes the count, it will trigger itself one more time because count is in its dependancies array. This can cause performance issues, and maybe in some case scenarios, if mouseClickCount isn’t reset to 0 before the hook is done, the conditions in the if statements can be met again and it would increase the value of counts resulting in unexpected results.

Also if we didn’t spot the issue at this point, we would have written unnecessary logic to avoid calling setCount when it shouldn’t be invoked.

Now for this very specific example, we have a few lines of code in the useEffect, but in other use cases we might have a lot more. Imagine we wanted to take out the logic (or part of it) inside the useEffect into its separate function (or more than one function) that the useEffect calls :

const [count, setCount] = useState(0);

const [mouseClickCount, setMouseClickCount] = useState(0); const checkCountAndMouseClicks = useCallback(() => {

if(mouseClickCount === 2 && count !== 0) {

setCount(count + 1);

} else if(mouseClickCount === 1 && count === 0) {

setCount(count + 1);

}

},[]); useEffect(() => {

checkCountAndMouseClicks();

}, [mouseClickCount]); ...

Do you see anything wrong in the previous code snippet ? our count will always equal 1 ! why is that ?

Well, useCallback memoizes the function its wrapping, including any variable references, so at the time of the memoization count equaled 0, and every time checkCountAndMouseClicks gets invoked, count is gonna be 0 even though its value might not be 0 .
['Abdalla Ahmed']
['React', 'Codingbootcamp', 'Hooks', 'Junior Developer', 'React Hook']