I feel like I come across this issue often.
When chaining useEffects to be triggered after state changes, I find that some of the useEffects in the chain have overlapping dependencies which cause them both to be triggered rather than sequentially, after one sets to state.
Example: I am triggering a chain of useEffects when chapterIndex
updates.
let [ chapterIndex, setChapterIndex ] = useState<number | null>(0);
let [textTransitioning, setTextTransitioning] = useState<'out' | 'in' | null>(null);
useEffect(() => {
setTextTransitioning('out')
}, [chapterIndex])
useEffect(() => {
if (chapterIndex !== null) {
const {
current: chapter = null
} = chapterRefs.current[chapterIndex];
if (textTransitioning === 'in') {
chapter?.classList.add('in');
}
}
}, [textTransitioning, chapterIndex])
How do I prevent both from running when chapterIndex
changes? I only want the second useEffect to run after the first useEffect sets to textTransitioning. When removing chapterIndex
from the dependency array I get the error: 'React Hook useEffect has a missing dependency: 'chapterIndex'. Either include it or remove the dependency array.'