I know there already are already some related questions, like How can React useEffect watch and update state?, but still, I don't get it totally.
Let's say I set an index state based on a prop; and I need to sanitize that value anytime it is set.
<MyComponent index={4}/>
This is how I attempted to do it:
useEffect(() => {
setIndex(props.index);
}, [props.index]);
useEffect(() => {
const sanitized = sanitizeIndex(index);
setIndex(sanitized);
},[index])
const sanitizeIndex = index => {
//check that index exists in array...
//use fallback if not...
//etc.
return index
}
It does not work (infinite loop), since the state is watched and updated by the second useEffect().
Of course, I could avoid this by calling sanitizeIndex() on the prop, so I only need a single instance of useEffect():
useEffect(() => {
setIndex(sanitizeIndex(props.index));
}, [props.index]);
Thing is, I call setIndex plenty of times in my code, and I fear to miss using sanitizeIndex.
Is there another way to "catch" and update a state value being set ?
Thanks !
props.index(and include the type ofindex: e.g.string/number/etc.) and also show the implementation ofsanitizeIndex, you'll get a better answer.