https://github.com/jmlweb/ismounted
React hook to check if the component is still mounted
https://github.com/jmlweb/ismounted
hook ismounted mounted react state
Last synced: 10 months ago
JSON representation
React hook to check if the component is still mounted
- Host: GitHub
- URL: https://github.com/jmlweb/ismounted
- Owner: jmlweb
- License: mit
- Created: 2019-04-21T19:24:30.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2024-09-24T07:06:03.000Z (almost 2 years ago)
- Last Synced: 2025-08-10T13:32:03.947Z (11 months ago)
- Topics: hook, ismounted, mounted, react, state
- Language: JavaScript
- Size: 465 KB
- Stars: 93
- Watchers: 1
- Forks: 10
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# isMounted
## ⚛ hook to check if your component is still mounted
Changing the state in an unmounted component will result in an error like this:
```
Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.
```
But in some cases (promises derived from an api call, timeouts or intervals...) it's impossible to know if the component is still mounted or not.
😎 Use this hook and avoid errors
```jsx
import React, { useState, useEffect } from 'react';
import useIsMounted from 'ismounted';
import myService from './myService';
import Loading from './Loading';
import ResultsView from './ResultsView';
const MySecureComponent = () => {
const isMounted = useIsMounted();
const [results, setResults] = useState(null);
useEffect(() => {
myService.getResults().then(val => {
if (isMounted.current) {
setResults(val);
}
});
}, [myService.getResults]);
return results ? : ;
};
export default MySecureComponent;
```
### Installing
`npm install ismounted` or `yarn add ismounted`