How to unmount a ReactJS node

In ReactJs, managing the mounting and unmounting of components is crucial for efficient rendering and performance. Unmounting a React node refers to the process of removing a component from the DOM (Document Object Model).

We will walk through the steps to unmount a ReactJS node using the ReactDOM.unmountComponentAtNode() method.

Prerequisites

Before proceeding, ensure that you have the following prerequisites installed.

  • Npm or yarn

  • Node.js

  • React

  • React DOM

If you don't have the React project setup, you can refer to this tutorial: How to Set Up React on Windows.

You can install react DOM using npm or yarn.

  • Using npm:

npm install react react-dom
  • Using yarn:

yarn add react react-dom

Import dependencies

In your JavaScript file, import the React and ReactDOM modules:

import React from 'react';
import ReactDOM from 'react-dom';

We will go through the following two ways to unmount a ReactJS node.

  • Using useState

  • Using unmountComponentAtNode

Using useState

For unmounting a react component using useState, follow the following steps and you may refer to the optional step.

Step 1: Import dependencies

In your JavaScript file, import useState from react module.

import {useState} from 'react':

Step 2: Create a state variable

Declare a state variable to keep track of whether the component should be mounted or unmounted.

const [showExample, setShowExample] = useState(true);

Step 3: Conditionally render the component

Render the component <MyComponent /> only if the showExample variable is true, otherwise render nothing.

{showExample && <MyComponent />}

Step 4: Unmount the component

To unmount the component, update the state variable isMounted to false.

const handleUnmount = () => {
setShowExample(false);
};

You can call this function to unmount the component.

Using unmountComponentAtNode

For unmounting a React component using unmountComponentAtNode, follow these steps.

Step 1: Identify the DOM element

In order to unmount a React component, you need to identify the DOM element where it is mounted. The DOM element serves as the container for the component. If you know the specific ID of the container DOM element, you can directly obtain the DOM element by its ID using the document.getElementById() method. For example we rendered App component in root in index.js:

ReactDOM.render(<App />, document.getElementById('root'));

So, if you want to unmount the App component you will get DOM element with an ID root like this.

// Get the DOM element by ID
const mountedElement = document.getElementById('root');

In the code snippet above, the document.getElementById() method is used to retrieve the DOM element containing the App component and store it in the mountedElement variable.

You can replace root with the actual ID of the container element in your application.

Step 2: Unmount the component

You can now unmount the component by calling the unmountComponentAtNode() method from ReactDOM and passing the DOM element reference as the argument.

ReactDOM.unmountComponentAtNode(mountedElement);

Optional step: component cleanup

Component cleanup is an optional step for unmounting the node. Unmounting a React component triggers its lifecycle methods, including componentDidMount() and componentWillUnmount().

The componentWillUnmount method is called just before the component is unmounted from the DOM. You can utilize this method to perform any necessary cleanup operations before the component is unmounted, such as canceling subscriptions or clearing intervals. This is important to prevent memory leaks and unwanted side effects that may occur if the interval continued to run after the component was no longer in the DOM.

// This method is called after the component has been added to the DOM
componentDidMount() {
// Setting up an interval that runs every second (1000 milliseconds)
this.interval = setInterval(() => {
console.log('Component mounted');
// Updating the state by incrementing the count
this.setState(prevState => ({
count: prevState.count + 1
}));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.intervalId);
console.log('Component unmounted and interval cleared');
}

In this method, we cleared the interval using clearInterval by passing in the intervalId that was stored during the componentDidMount phase. This ensures that the interval is stopped and no longer continues to execute after the component is unmounted.

Additionally, we logged a message to the console indicating that the component has been unmounted and the interval has been cleared.

Run application

Run the application by following the command.

npm start

To run the sample application, execute the following code.

import React,{useState} from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './components/MyComponent';

const App = () => {
  const [isMounted, setIsMounted] = useState(true);
  const handleUnmountUnmountFunc = () => {
    const rootElement = document.getElementById('root');
    ReactDOM.unmountComponentAtNode(rootElement);
  };
  const handleUnmountUseState = () => {
    setIsMounted(false);
  };

  return (
    <div>
      <h1>Unmounting Example</h1>
      <MyComponent />
      {isMounted && <MyComponent />}
      {isMounted && <button onClick={handleUnmountUseState}>Unmount using useState</button>}
      {!isMounted && <button onClick={handleUnmountUnmountFunc}>Unmount Using unmountComponentAtNode()</button>}
    </div>
  );
};

export default App;
App that unmounts "MyComponent" using useState and "App" using unmountComponentAtNode()

Explanation

The main component of the application is the App component, which renders the MyComponent component. The app first gives the option to unmount MyComponent, which is implemented by using useState. After MyComponent is unmounted, the app gives the option to unmount App, which is implemented using unmountComponentAtNode().

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved