How to conditionally call useEfect?
I need to call useEffect hook, but unless two conditions will be true
Something like this :
useEffect(() => {
console.log('PRINT SOMETHING ')
}, [reduxState.age > 26 && reduxState.employee === true])
I know i could insert those conditions inside useEffect with if
, and do whatever i want.
But the problem is that i have another tab with very similar useEffect.
And i need to somehow separete them.
In order to not call unwanted useEffect from another Tab.
Would it be possible ?
React shallow compares the dependency array with previous values and if it changes it will run useEffect.
So in your example if you change reduxState.age from 27 to 28 the deps array is still true and useEffect is not triggered.
Correct way is to put the condition inside useEffect. You can have more conditions in one useEffect or you can write more useEffects.
useEffect(() => {
if (reduxState.age < 18 && reduxState.employee === true)
console.log('Employee younger than 18');
if (reduxState.age > 26 && reduxState.employee === true)
console.log('Employee older than 26');
}, [reduxState.age, reduxState.employee])
or
useEffect(() => {
if (reduxState.age < 18 && reduxState.employee === true)
console.log('Employee younger than 18');
}, [reduxState.age, reduxState.employee])
useEffect(() => {
if (reduxState.age > 26 && reduxState.employee === true)
console.log('Employee older than 26');
}, [reduxState.age, reduxState.employee])
This is common usage.