I have multiple values I'm listening to and different actions to perform for those values. Problem is that I don't know what is the best way to prevent them from running on first render. Let's say I have:
const [firstValue, setFirstValue] = useState();
const [secondValue, setSecondValue] = useState();
const [thirdValue, setThirdValue] = useState();
const [fourthValue, setFourthValue] = useState();
const [fifthValue, setFifthValue] = useState();
useEffect(()={
// action 1
},[firstValue, secondValue, thirdValue])
useEffect(()={
// action 2
},[fourthValue])
useEffect(()={
// action 3
},[fifthValue])
I looked into isMounted = useRef(false)
example, but it works only if you have just 1 extra useEffect
.
CodePudding user response:
If the expected functionality is to prevent execution of a code inside useEffect during initial rendering, just keep the code inside an if condition which will check if each of the states have the values that is not the initial value of that state.
Ex:
const [firstValue, setFirstValue] = useState(null);
const [secondValue, setSecondValue] = useState(null);
const [thirdValue, setThirdValue] = useState(null);
const [fourthValue, setFourthValue] = useState(null);
const [fifthValue, setFifthValue] = useState(null);
useEffect(()={
if(firstValue!==null&&secondValue!==null&&thirdValue!==null){
// action 1
}
},[firstValue, secondValue, thirdValue])
CodePudding user response:
I looked into
isMounted = useRef(false)
example, but it works only if you have just 1 extrauseEffect
.
I think you are assuming you must update the isMounted
ref within the first useEffect
hook in the component.
Remember that all hooks are called each render cycle in the order they are declared. If you want all three useEffect
hooks to skip the initial render then don't update the isMounted
ref until after all three have had a chance to run at least once.
Example:
const [firstValue, setFirstValue] = useState();
const [secondValue, setSecondValue] = useState();
const [thirdValue, setThirdValue] = useState();
const [fourthValue, setFourthValue] = useState();
const [fifthValue, setFifthValue] = useState();
const isMountedRef = useRef(false);
useEffect(()={
// action 1
}, [firstValue, secondValue, thirdValue]);
useEffect(()={
// action 2
}, [fourthValue]);
useEffect(()={
// action 3
}, [fifthValue]);
useEffect(() => {
isMountedRef.current = true; // <-- now mutate the ref
}, []);