Member-only story
Should You Stop Using isMounted in React?
Overcoming one of the oldest antipatterns in React
If you are familiar with the React component lifecycle, you know that a React component goes through a mounting stage and an unmounting stage. If you have used class components, then you have used lifecycle hooks such as componentDidMount
and componentWillUnmount
to set up and clean up the component.
With React’s move to functional components and hooks a few years back, a lot of developers were left confused because there were no hooks along the lines of useIsMounted
, useDidMount
and useWillUnmount
. Some developers and libraries have also created custom hooks for this purpose.
Before ES6 classes support, React had a isMounted
method, that a lot of developers were using as an antipattern. Let's look at how many developers, including myself, repeated the pattern in ES6 classes and functional components, respectively.
In ES6 classes, we went back to the antipattern by doing the following: