3 ms·
How do you handle a useEffect that relies on state, but you don't want it to run on first render? I usually have a separate state that is "firstLoad" and toggle
by WesleyJohnson 6y ago
How do you handle a useEffect that relies on state, but you don't want it to run on first render? I usually have a separate state that is "firstLoad" and toggle that in the effect and exit out, then its free to run on successive invocations. But typing this out - it makes me the think the dependent state itself should be driving if it runs or not...
- sickcodebruh 6y agoI don't think there's a way around tracking that `firstLoad` value. A `ref` is probably a better choice than a separate state value because you don't need to render when the component becomes aware that you're past the first render. You could do it in a simple hook: function useFirstRenderComplete() { const renderCountRef = useRef(0); useEffect(() => { if (renderCountRef.current) { return; } renderCountRef.current += 1; }, []); return renderCountRef.current !== 0; }