EN
React - is component mounted hook
5 points
In this short article, we would like to show how to create React hook that stores information about component is mount or removed.
Quick solution:
xxxxxxxxxx
1
const useMountedRef = (callback, dependences) => {
2
const mountedRef = useRef(false);
3
useEffect(() => {
4
mountedRef.current = true;
5
return () => {
6
mountedRef.current = false;
7
};
8
}, []);
9
return mountedRef;
10
};
11
12
// Usage example:
13
14
const mountedRef = useMountedRef();
15
16
// mountedRef.current // true/false
Note: the main advantage of the solution is the possibility to access the current state in different places with React reference (by accessing
mountedRef.current
).
In this section we present an example where the programmer is able to check if the component is still mounted after some async operation - it let to decide if we can set a new state for some hook inside the component.
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const useMountedRef = (callback, dependences) => {
6
const mountedRef = React.useRef(false);
7
React.useEffect(() => {
8
mountedRef.current = true;
9
return () => {
10
mountedRef.current = false;
11
};
12
}, []);
13
return mountedRef;
14
};
15
16
// Usage example:
17
18
const App = () => {
19
const mountedRef = useMountedRef();
20
const handleClick = () => {
21
// it is place to put AJAX / Fetch request to server
22
// next line simulates response recived from server after 1 second
23
setTimeout(() => {
24
// if mountedRef.current stores true, we know the component is mount and we can bind data
25
console.log(`Component mounted: ${mountedRef.current ? 'Yes' : 'No'}`);
26
}, 1000);
27
};
28
return (
29
<button onClick={handleClick}>Request backend</button>
30
);
31
};
32
33
const root = document.querySelector('#root');
34
ReactDOM.render(<App />, root);