Cleaning up after components

In this final section of the chapter, we'll think about cleaning up after components. You don't have to explicitly unmount components from the DOM—React handles that for us. There are some things that React doesn't know about and therefore cannot clean up for us once the component is removed.

It's for these types of circumstance that the componentWillUnmount() lifecycle method exists. The main use case for cleaning up after React components is asynchronous code.

For example, imagine a component that issues an API call to fetch some data when the component is first mounted. Now, imagine that this component is removed from the DOM before the API response arrives.

Cleaning up asynchronous calls

If your asynchronous code tries ...

Get React and React Native now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.