This brings us to the next piece of knowledge that we should know about setState and that is it can take a callback function. Let’s fix our code!
First, setState is asynchronous. This means state won’t update exactly after you call setState and this can lead to some aggravating behavior which we will hopefully now be able to avoid!
… you remove a component from the DOM, React runs componentWillUnmount right before it gets removed. You should use this method to clean up any open connections such as WebSockets or intervals.