I have a usecase where i need to unmount my react component. But in some cases, the particular react component is unmounted by a different function. Hence, I need to check if the component is mounted before unmounting it.
-
https://nextjs.org/docs/messages/react-hydration-error – Pavel Fedotov Aug 26 '23 at 02:58
14 Answers
Since isMounted()
is being officially deprecated, you can do this in your component:
componentDidMount() {
this._ismounted = true;
}
componentWillUnmount() {
this._ismounted = false;
}
This pattern of maintaining your own state
variable is detailed in the ReactJS documentation: isMounted is an Antipattern.

- 6,022
- 8
- 33
- 66

- 270,417
- 55
- 406
- 400
-
6Thanks for the tip ... from the docs ... Just set a _isMounted property to true in componentDidMount and set it to false in componentWillUnmount ... however, using this.setState({mounted: false}); may trigger too late to prevent the warning since state changes do not happen immediately - better to just use a class property for this ... this.mounted = false - thanks tho, this pointed me in the right direction – danday74 Sep 18 '17 at 12:44
-
2@danday74, yeah you are correct. I probably missed the point when I wrote the answer. Consider upvoting the answer if it helped – Shubham Khatri Sep 18 '17 at 13:10
-
3@KevinGhaboosi, Unfortunately only the person who asked the question would be able to accept this as an answer – Shubham Khatri Jan 20 '18 at 19:14
-
"Read the anti-pattern link more carefully. Using the method `isMounted()` is an anti-pattern, but using a property, like `_isMounted` is recommended." https://stackoverflow.com/questions/49906437/how-to-cancel-a-fetch-on-componentwillunmount#comment117946008_49906662 – tim-phillips Aug 24 '22 at 00:44
-
If the component had already unmounted then won't `this._ismounted` be undefined? – darKnight Jun 15 '23 at 11:46
I'll be recommended you to use the useRef
hook for keeping track of component is mounted or not because whenever you update the state then react will re-render the whole component and also it will trigger the execution of useEffect or other hooks.
function MyComponent(props: Props) {
const isMounted = useRef(false)
useEffect(() => {
isMounted.current = true;
return () => { isMounted.current = false }
}, []);
return (...);
}
export default MyComponent;
and you check if the component is mounted with if (isMounted.current) ...
-
Use https://stackoverflow.com/a/39767963/1783174 for class components. Use this for hooks. – publicJorn Nov 24 '20 at 11:02
-
Did you mean to say you **do** recommend use of `useState` instead of "don't"? Because your solution seems to use it – T J Jun 23 '21 at 06:13
-
The cleanup function will be called if you have multiple useEffects in the single component, so this does not work, as it would not differ between re-renders and re-mounts. – oligofren Dec 30 '21 at 10:40
-
"Additionally, if a component renders multiple times (as they typically do), the previous effect is cleaned up before executing the next effect." https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect – oligofren Dec 30 '21 at 10:40
-
The effect isn't re-executed after mount, since its dependency array is empty. – Nathanael Feb 22 '22 at 19:54
I think that Shubham answer is a workaround suggested by react for people that need to transition their code to stop using the isMounted
anti-pattern.
This is not necessarily bad, but It's worth listing the real solutions to this problem.
The article linked by Shubham offers 2 suggestions to avoid this anti pattern. The one you need depends on why you are calling setState when the component is unmounted.
if you are using a Flux store in your component, you must unsubscribe in componentWillUnmount
class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
render() {
...
}
componentWillUnmount() {
mydatastore.unsubscribe(this);
}
}
If you use ES6 promises, you may need to wrap your promise in order to make it cancelable.
const cancelablePromise = makeCancelable(
new Promise(r => component.setState({...}}))
);
cancelablePromise
.promise
.then(() => console.log('resolved'))
.catch((reason) => console.log('isCanceled', reason.isCanceled));
cancelablePromise.cancel(); // Cancel the promise
Read more about makeCancelable
in the linked article.
In conclusion, do not try to patch this issue by setting variables and checking if the component is mounted, go to the root of the problem. Please comment with other common cases if you can come up with any.

- 4,831
- 3
- 36
- 42
-
Imagine a list of posts. Each post is a separate component and has a delete button next (inside) to it. When user clicks the button, post sets `isDeleting = true` (to disable the button), tells the parent component to delete the post (using callback passed via props), and when he's done (another callback, but to the post component) it might need to enable the button. E.g. when HTTP error occurs (post has not been deleted). That is, the post component might need to change state depending on whether it's still mounted or not. Is there anything wrong with that? – x-yuri Jul 27 '18 at 07:19
-
3Just to point out for anyone still coming here. The `makeCancelable` method in the article referenced to is setting a local variable - just like Shubham's example. There is no way of actually cancelling a Promise. I have a hard time to see why setting a boolean in some other place would be better that having it clearly in the React component. The point about unsubscribing subscriptions is valid though. – Clara Attermo Mar 10 '21 at 09:11
-
My component sets a proxy on an object's property. When that object updates, the proxy calls `setState` so that the property and the component's state are in sync. So in this case the suggestions are irrelevant. – Alto May 19 '21 at 05:19
Another solution would be using Refs . If you are using React 16.3+, make a ref to your top level item in the render function.
Then simply check if ref.current is null or not.
Example:
class MyClass extends React.Component {
constructor(props) {
super(props);
this.elementRef = React.createRef();
}
checkIfMounted() {
return this.elementRef.current != null;
}
render() {
return (
<div ref={this.elementRef} />
);
}
}

- 1,292
- 10
- 16
Using @DerekSoike answer, however in my case using useState
to control the mounted state didn't work since the state resurrected when it didn't have to
What worked for me was using a single variable
myFunct
was called in a setTimeout
, and my guess is that when the same component initialized the hook in another page it resurrected the state causing the memory leak to appear again
So this didn't work for me
const [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(true)
return () => setIsMounted(false)
}, [])
const myFunct = () => {
console.log(isMounted) // not always false
if (!isMounted) return
// change a state
}
And this did work for me
let stillMounted = { value: false }
useEffect(() => {
stillMounted.value = true
return () => (stillMounted.value = false)
}, [])
const myFunct = () => {
if (!stillMounted.value) return
// change a state
}

- 4,011
- 10
- 49
- 90
-
This worked while the previous strategy (which is updated at many places didn't)... Thanks @GWorking – Akber Iqbal Jan 22 '20 at 04:01
-
it will reload the functional component is we update isMounted state to true or false instead I'll recommended use the let variable. – Sagar Sep 03 '20 at 08:19
I got here because I was looking for a way to stop polling
the API.
The react docs does cover the websocket
case, but not the polling one.
The way I worked around it
// React component
React.createClass({
poll () {
if (this.unmounted) {
return
}
// otherwise, call the api
}
componentWillUnmount () {
this.unmounted = true
}
})
it works. Hope it helps
Please, let me know if you guys know any failing test case for this =]

- 833
- 7
- 13
-
it works, but what if you have multiple instances? all will take a reference to the same `allowPolling` – stackoverflow Mar 24 '18 at 12:24
-
If you're using hooks:
function MyComponent(props: Props) {
const [isMounted, setIsMounted] = useState<boolean>(false);
useEffect(() => {
setIsMounted(true);
}, []);
useEffect(() => {
return () => {
setIsMounted(false);
}
}, []);
return (...);
}
export default MyComponent;

- 11,238
- 3
- 79
- 74
-
This post https://dev.to/trentyang/replace-lifecycle-with-hooks-in-react-3d4n would help to give more details of how to convert from React Native Class style to React Hooks style – garykwwong Dec 22 '19 at 03:12
-
1@ZiaUlRehmanMughal The first `useEffect` hook is called once on component mount since an empty array is passed as the dependencies list. The second `useEffect` hook is passed a clean up function that gets called on unmount. Take a look at the docs for more detail: https://reactjs.org/docs/hooks-reference.html#useeffect - – Derek Soike Mar 10 '20 at 15:44
-
1This is a memory leak. You are calling `setState` on a component that has been unmounted. I suggest people to use this other [answer](https://stackoverflow.com/a/63719707/2089675) – smac89 Aug 26 '21 at 17:58
The same idea but enother implementation
/**
* component with async action within
*
* @public
*/
class MyComponent extends Component {
constructor ( ...args ) {
// do not forget about super =)
super(...args);
// NOTE correct store "setState"
let originSetState = this.setState.bind(this);
// NOTE override
this.setState = ( ...args ) => !this.isUnmounted&&originSetState(...args);
}
/**
* no necessary setup flag on component mount
* @public
*/
componentWillUnmount() {
// NOTE setup flag
this.isUnmounted = true;
}
/**
*
* @public
*/
myCustomAsyncAction () {
// ... code
this.setState({any: 'data'}); // do not care about component status
// ... code
}
render () { /* ... */ }
}

- 401
- 3
- 14

- 121
- 1
- 5
I have solve with hot reload and react to different it events ✅
const {checkIsMounted} = useIsMounted(); //hook from above
useEffect(() => {
//here run code
return () => {
//hot reload fix
setTimeout(() => {
if (!checkIsMounted()) {
//here we do unmount action
}
}, 100);
};
}, []);

- 21
- 2
Pproblem
There is a problem when using the useState() hook. If you are also trying to do something else in a useEffect function (like fetching some data
when the component is mounted
) at the same time with setting the new value
for the hook,
const [isMounted, setIsMounted] = useState(false)
useEffect(() =>
{
setIsMounted(true) //should be true
const value = await fetch(...)
if (isMounted) //false still
{
setValue(value)
}
return () =>
{
setIsMounted(false)
}
}, [])
the value of the hook will remain the same
as the initial value (false), even if you have changed it in the beggining. It will remain unchanged for that first render
, a new re-render being required for the new value to be applied.
For some reason @GWorking solution did not work too. The gap appears to happen while fetching, so when data arrives the component is already unmounted.
Solution
You can just combine both
and and check if the component is unmounted during any re-render
and just use a separate
variable that will keep track to see if the component is still
mounted during that render time period
const [isMounted, setIsMounted] = useState(false)
let stillMounted = { value: false }
useEffect(() =>
{
setIsMounted(true)
stillMounted.value = true
const value = await fetch(...)
if (isMounted || stillMounted.value) //isMounted or stillMounted
{
setValue(value)
}
return () =>
{
(stillMounted.value = false)
setIsMounted(false)
}
}, [isMounted]) //you need to also include Mounted values
Hope that helps someone!

- 405
- 1
- 8
- 17
There's a simple way to avoid warning
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
You can redefine setState
method inside your class component using this pattern:
componentWillUnmount() {
this._unmounted = true;
}
setState(params, callback) {
this._unmounted || super.setState(params, callback);
}

- 302
- 4
- 7
This may be irrelevant to the OP's question, but I came here from google and I didn't find my answer here, so I wrote one:
import {useEffect, useRef} from 'react';
export function useUnmounted(effect) {
const callbackRef = useRef(effect);
useEffect(() => {
callbackRef.current = effect;
}, [effect]);
useEffect(() => {
return () => {
callbackRef.current();
};
}, []);
}
usage:
// somewhere in your component:
useUnmounted(() => {
// do something before getting unmounted
});

- 1
- 2
i found that the component will be unmounted, generate fill this var
if(!this._calledComponentWillUnmount)this.setState({vars});

- 179
- 1
- 9
-
4this is an internal property, I don't think it's safe to play with them because it might change in the future. – stackoverflow Mar 24 '18 at 12:23
-
Well, to be honest, it is safe until you update the library, so in some cases, it is a good solution. But there should be a condition `!== undefined` to be sure that property is there. – extempl Oct 11 '18 at 16:31
-
You can use:
myComponent.updater.isMounted(myComponent)
"myComponent" is instance of your react component. this will return 'true' if component is mounted and 'false' if its not..
- This is not supported way to do it. you better unsubscribe any async/events on componentWillUnmount.

- 150
- 3
-
-
-
3@NourSIDAOUI This feature is officially deprecated since 2016. https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html – Wojtek322 Apr 20 '22 at 12:40