Sometimes, we want to check if the React component is unmounted.
In this article, we’ll look at how to check if the React component is unmounted.
Check if the React Component is Unmounted
To check if the React component is unmounted, we can set a state in the callback that’s returned in the useEffect hook callback.
For instance, we can write:
import React, { useEffect, useState } from "react";
export default function App() {
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
setIsMounted(true);
return () => setIsMounted(false);
}, []);
return <div>{isMounted.toString()}</div>;
}
We create the isMounted state with the useState hook.
Then we call the useEffect hook with a callback that calls setIsMounted to set isMounted to true .
And since the function that’s returned in the useEffect callback runs when the component unmounts, we can call setIsMounted to set isMounted to false there.
Finally, we render the value of isMounted is the div.
Conclusion
To check if the React component is unmounted, we can set a state in the callback that’s returned in the useEffect hook callback.