Languages
[Edit]
EN

React - is component mounted hook

5 points
Created by:
Remy-Lebe
802

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:

const useMountedRef = (callback, dependences) => {
	const mountedRef = useRef(false);
    useEffect(() => {
      	mountedRef.current = true;
      	return () => {
        	mountedRef.current = false;
        };
    }, []);
  	return mountedRef;
};

// Usage example:

const mountedRef  = useMountedRef();

// 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).

 

Practical example

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.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const useMountedRef = (callback, dependences) => {
	const mountedRef = React.useRef(false);
    React.useEffect(() => {
      	mountedRef.current = true;
      	return () => {
        	mountedRef.current = false;
        };
    }, []);
  	return mountedRef;
};

// Usage example:

const App = () => {
    const mountedRef  = useMountedRef();
  	const handleClick = () => {
        // it is place to put AJAX / Fetch request to server
        // next line simulates response recived from server after 1 second
    	setTimeout(() => {
          	// if mountedRef.current stores true, we know the component is mount and we can bind data
        	console.log(`Component mounted: ${mountedRef.current ? 'Yes' : 'No'}`);
        }, 1000);
    };
    return (
        <button onClick={handleClick}>Request backend</button>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join