I am testing React.useEffect
and noticed an interesting behavior that I can't explain.
When I run the code below and click on the button a few times, I see the following output which is missing the useEffect console for count = 1
import React from 'react';
export function App(props) {
const [count, setCount] = React.useState(0)
console.log('ran app')
React.useEffect(() => {
console.log("ran effect", count)
}, [count < 2])
return (
<div className='App'>
<button onClick={() => setCount(count 1)}>click</button>
<h3>{count}</h3>
</div>
);
}
ran app
ran effect
0
ran app // this is where I expect to see ran effect for count = 1 but I don't
ran app
ran effect
2
ran app
ran app
However if I remove the expression count<2
from the dependencies, I see ran useeffect
for count = 1
as well.
CodePudding user response:
Generally an effect is applied after every single render. However react allows you to customize that by passing an array with values as an optional second argument. In your case, that is [count < 2]
. When you pass such a value, the effect is applied only when that value changes.
In your case, the effect would run only when the boolean count < 2
which is True initially, changes to False when count is 2.
Take a look at the official documentation for useEffect
here https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
CodePudding user response:
Because the condition result (county < 2) doesn't change when the count changes from 0 to 1.