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.
createRoot()Unmounting works at the root level. Once a root is unmounted, React destroys all associated state, event listeners, and effects tied to that root.
// 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);
// 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();
// 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 />);
Test the concept below. When mounted, an "App" runs (simulated by a timer). When unmounted, the DOM is cleared and the timer stops.
When root.unmount() is called, React removes the entire component tree and runs all cleanup logic, freeing memory and preventing leaks.
createRoot() with root.unmount()useEffect cleanup for component-level cleanupcreateRoot()Goal: Master safe and efficient unmounting in modern React.