I will add here: No not update state on component unmount. Very common mistake that also is in one of your examples:
import{useState}from"react";functionApp(){const[count,setCount]=useState(0);// Directly update stateconstupdate=()=>setCount(count+1);// Directly update state after 3 secconstasyncUpdate=()=>{setTimeout(()=>{setCount((currentCount)=>currentCount+1);},2000);};// Render UIreturn(<divclassName='App'><span>Count:{count}</span>
<buttononClick={update}>Add+1</button>
<buttononClick={asyncUpdate}>Add+1later</button>
</div>
);}exportdefaultApp;
asyncUpdate method create timer that after 3 seconds, updates component state. After 3 seconds, the component may be unmounted (and timer still running in bacground since you didn't clean it), and we have a memory leak.
Two notes here:
always clear timeouts/intervals
check if component is mounted in your async code
constmounted=useRef(false);lettimeoutHandler=null;useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;// clear timeout on component unmountif(timeoutHandler){clearTimeout(timeoutHandler)}};},[]);constasyncUpdate=()=>{// still caveat here, multiple calls to asyncUpdate will overide timeoutHandler so we should clear it here befeore create new oneif(timeoutHandler){clearTimeout(timeoutHandler)}timeoutHandler=setTimeout(()=>{// do not update component state when is not mountedif(mounted.current){setCount((currentCount)=>currentCount+1);}},2000);};
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I will add here: No not update state on component unmount. Very common mistake that also is in one of your examples:
asyncUpdate
method create timer that after 3 seconds, updates component state. After 3 seconds, the component may be unmounted (and timer still running in bacground since you didn't clean it), and we have a memory leak.Two notes here: