How to trigger useEffect only once when state of a variable changes the first time from null to something?
In the case below, state.gender
changes from null
to 0
or 1
. The useEffect should only trigger when it changes the first time. Thereafter, the subsequent switches between values 0
and 1
should not trigger useEffect.
const [state, setState] = useState({
screen: 1,
gender: null,
});
useEffect(() => {
// Do something
})}
}, [state.gender]);
...
...
...
<RadioGroup
aria-labelledby="gender-group"
name="gender"
value={state.gender}
onChange={(event, fieldValue) => {handleInputChange(event, fieldValue, "gender")}}
>
<FormControlLabel value={1} control={<Radio />} label="Female" />
<FormControlLabel value={0} control={<Radio />} label="Male" />
</RadioGroup>
CodePudding user response:
You can use a ref
for that
const firedRef = useRef(false);
useEffect(() => {
if (firedRef.current || state.gender === null) return;
firedRef.current = true;
// rest of the code goes here
}, [state.gender]);
CodePudding user response:
If your initial value is null
, and then you just switch between 0
and 1
, then stop the operation if the value is null
useEffect(() => {
if(state.gender !== null) return;
// Do something
}, [state.gender]);
CodePudding user response:
Removed useEffect and added onClick handling which checks if state was null before. useEffect was not needed in this case as constantly monitoring a state was not necessary.
const handleGenderChange = (event, fieldValue) => {
//trigger geo only when gender changes from null to a value (1st time)
if(state.gender == null) {
attemptLocation();
}
//update gender state
handleInputChange(event, fieldValue, "gender")
}