← Back to Chapters

Unmounting Components

? Unmounting Components

? Quick Overview

In React 18+, root.unmount() is the official way to remove a React component tree from the DOM. It replaces the legacy unmount APIs and ensures complete cleanup of state, effects, and subscriptions.

? Key Concepts

  • Unmounting removes the entire React component tree
  • React 18 uses createRoot()
  • Cleanup happens automatically and consistently
  • Essential for micro-frontends and dynamic apps

? Syntax & Theory

Unmounting works at the root level. Once a root is unmounted, React destroys all associated state, event listeners, and effects tied to that root.

? Old Method (React 17 and below)

? View Code Example
// React 17 unmounting using legacy API
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

const rootElement = document.getElementById("root");

ReactDOM.render(<App />, rootElement);

ReactDOM.unmountComponentAtNode(rootElement);

? New Method (React 18+)

? View Code Example
// React 18 unmounting using createRoot
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const container = document.getElementById("root");
const root = createRoot(container);

root.render(<App />);

root.unmount();

? Conditional Mounting Example

? View Code Example
// Toggle mounting and unmounting dynamically
import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const container = document.getElementById("root");
const root = createRoot(container);

function Controller() {
const [mounted, setMounted] = useState(true);

return (
<div>
<button onClick={() => {
if (mounted) root.unmount();
else root.render(<App />);
setMounted(!mounted);
}}>
{mounted ? "Unmount App" : "Mount App"}
</button>
</div>
);
}

root.render(<Controller />);

? Interactive Simulation

Test the concept below. When mounted, an "App" runs (simulated by a timer). When unmounted, the DOM is cleared and the timer stops.

Status: Waiting...
#root is empty

? Live Explanation

When root.unmount() is called, React removes the entire component tree and runs all cleanup logic, freeing memory and preventing leaks.

? Use Cases

  • Micro-frontend architectures
  • Embedding React in non-React pages
  • Resetting app state completely
  • Performance optimization

? Tips & Best Practices

  • Always match createRoot() with root.unmount()
  • Avoid frequent unmounting unless necessary
  • Prefer useEffect cleanup for component-level cleanup
  • Unmount only entire roots, not individual components

? Try It Yourself

  1. Create a React 18 app using createRoot()
  2. Unmount the root from the console
  3. Toggle mounting dynamically
  4. Observe memory cleanup in DevTools

Goal: Master safe and efficient unmounting in modern React.