I have set up an effect inside my component, which changes the view if another state attribute changes. But for some reason, when the component mounts, the effect is run, even though the value of detailIndex has not changed.
const EventsSearchList = () => { const [view, setView] = useState('table'); const [detailIndex, setDetailIndex] = useState(null); useEffect(() => { console.log('onMount', detailIndex); // On mount shows "null" }, []); useEffect( a => { console.log('Running effect', detailIndex); // On mount shows "null"!! Should not have run... setView('detail'); }, [detailIndex] ); return <div>123</div>; }; Why is this happening?
UPDATE: In case it is not clear, what I am trying is to run the effect when the component updates because detailIndex changes. NOT when it mounts.
useEffectsalways fires on mount AFAIK.[]useState(undefined)instead onuseState(null). My dumb first thought is that, your state was previously undefined and you just set it to null, so useEffect is triggered. But it is more likely that useEffect is always executed on mount even though you passed a dependecy value.