Rendering & ReactDOM
Before you can build anything with React, you need to understand how React actually puts pixels on the screen. This chapter goes deep into ReactDOM.createRoot(), the Virtual DOM and why it exists, the reconciliation & diffing algorithm React uses to update the browser efficiently, every render trigger, React.StrictMode, Portals, server-side hydration, and the performance rules that flow directly from how rendering works.
1. ReactDOM & createRoot()
ReactDOM is the package that bridges React's component tree with the
actual browser DOM. It lives in the separate
react-dom package (not in react
itself), because React's core is platform-agnostic — the same core powers React Native, React
Three Fiber, and other renderers.
createRoot() — introduced in React 18 — is the
entry point that attaches your React application to a real DOM node.
Every React app calls it exactly once in src/main.jsx.
import ReactDOM from 'react-dom' import App from './App' ReactDOM.render( <App />, document.getElementById('root') ) // ❌ Synchronous, blocks thread // ❌ No concurrent features // ❌ Deprecated in React 18
import { createRoot } from 'react-dom/client' import App from './App' const root = createRoot( document.getElementById('root') ) root.render(<App />) // ✅ Enables concurrent rendering // ✅ Automatic batching // ✅ Transitions & Suspense
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import './index.css'
// 1. Find the #root div in index.html
const container = document.getElementById('root')
// 2. Create a React root attached to that DOM node
const root = createRoot(container)
// 3. Render the App component tree into the root
root.render(
<StrictMode>
<App />
</StrictMode>
)
// root.render() can be called again to update the UI
// (e.g. hot reload) — React diffs against previous treereact-dom/client
contains the browser-specific APIs. The old react-dom import still works for legacy APIs like
flushSync.
createRoot opts your app into
Concurrent Mode — React can interrupt, pause, and resume rendering
work, enabling Suspense and Transitions.
createRoot() once per
application. React manages the entire component tree from that single root — you never
call it again after init.createRoot() on multiple DOM nodes to embed React
inside existing non-React pages. Each root is independent.2. The React Render Pipeline
Every time React needs to update the screen, it goes through a four-phase pipeline. Understanding this pipeline is the foundation for understanding performance, side-effects, and why React behaves the way it does:
setState call, prop change, context update, or the
initial root.render().useEffect cleanup here.
useEffect callbacks after the browser
paints, so they don't block the UI.
3. The Virtual DOM — Why React Doesn't Touch the Real DOM Directly
The real browser DOM is slow to update — every DOM mutation can trigger layout recalculation, reflow, and repaint. React's solution: maintain a lightweight Virtual DOM — a JavaScript object representation of the UI tree — and only apply the minimal diff to the real DOM.
// What you write (JSX):
<div className="card">
<h2>Hello React</h2>
<p>Count: {count}</p>
</div>
// What React creates internally (a plain JS object):
{
type: 'div',
props: {
className: 'card',
children: [
{
type: 'h2',
props: { children: 'Hello React' }
},
{
type: 'p',
props: { children: ['Count: ', 5] }
}
]
}
}
When state changes (e.g. count goes from 5 → 6),
React builds a new Virtual DOM tree and diffs it against the
previous one. Only the changed node gets patched in the real DOM:
4. Reconciliation & the Diffing Algorithm
Reconciliation is React's process of comparing the new Virtual DOM tree against the previous one to decide what changed. React uses a highly optimised heuristic diffing algorithm (O(n) instead of the theoretically optimal O(n³)) based on two key assumptions:
div → span), React
destroys the old tree and builds a new one from scratch. If the type is the
same, React updates the existing DOM node's attributes.
key
prop to match children across renders. Stable unique keys let React reorder, insert and
remove items without re-mounting everything.React.memo() or PureComponent skip re-rendering if their props haven't
changed — React bails out of the render phase entirely.Type change destroys state — a common gotcha
// isLoggedIn true → renders <AdminPanel /> // isLoggedIn false → renders <GuestPanel /> // ↑ Different component at same position // → React unmounts one, mounts the other // → ALL state inside is reset! {isLoggedIn ? <AdminPanel /> : <GuestPanel /> }
// Same component type <Panel /> // React reuses the DOM node // and updates props only. // State inside Panel is preserved! <Panel isAdmin={isLoggedIn} />
key. When the key changes, React unmounts the old
component and mounts a fresh one — state is reset completely.
<Form key={userId} /> — when
userId changes, React creates a brand new
Form with empty state.
5. What Triggers a Re-render?
React only re-renders a component when it has a reason to. Understanding the exact triggers prevents unnecessary re-renders and helps you reason about why a component updated when you didn't expect it:
// Calling setState (useState setter) always triggers a re-render function Counter() { const [count, setCount] = useState(0) // ✅ Triggers re-render — new value differs const increment = () => setCount(count + 1) // ⚠️ Triggers re-render even if value is same! const noOp = () => setCount(0) // still re-renders (React 17 behaviour) // ✅ React 18 bails out if same value (Object.is comparison) const safeNoOp = () => setCount(prev => prev) // no re-render if unchanged return <button onClick={increment}>Count: {count}</button> }
// A child re-renders whenever its parent re-renders // (even if props haven't actually changed!) function Parent() { const [count, setCount] = useState(0) return ( <div> <button onClick={() => setCount(c => c + 1)}>+</button> // Child re-renders on every click even though // its "title" prop never changes! <Child title="Hello" /> </div> ) } // ✅ Wrap in React.memo() to skip if props unchanged const Child = React.memo(function Child({ title }) { console.log('Child rendered') return <p>{title}</p> })
// Any component that consumes a Context re-renders // when that Context value changes const ThemeContext = React.createContext('light') function App() { const [theme, setTheme] = useState('light') return ( <ThemeContext.Provider value={theme}> <Page /> {/* re-renders when theme changes */} <Sidebar /> {/* re-renders when theme changes */} </ThemeContext.Provider> ) } // Split contexts to limit re-renders: // ThemeContext (rarely changes) vs UserContext (often changes)
// Parent re-render → all children re-render by default // React renders the full subtree unless blocked by memo() // ✅ Lifting children UP avoids unnecessary re-renders function Parent() { const [count, setCount] = useState(0) return ( <div> <button onClick={() => setCount(c => c + 1)}>{count}</button> {/* Passing children as prop — StaticContent doesn't re-render! */} {props.children} </div> ) } // <Parent><StaticContent /></Parent> — StaticContent stays stable
| Trigger | Who re-renders? | How to prevent |
|---|---|---|
setState() called |
That component + all descendants | React.memo on children |
| Props change | The child that received new props | React.memo() |
| Context value changes | All consumers of that context | Split contexts, useMemo for value |
| Parent re-renders | All children by default | React.memo(), lift children |
forceUpdate() |
That component only (class) | Avoid — use state instead |
6. React.StrictMode — Your Safety Net in Development
<StrictMode> is a development-only tool that
helps you find bugs early. It does nothing in production — zero
performance impact in your deployed app. In development, it activates extra checks
and warnings by intentionally doing certain things twice.
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
)
// StrictMode can also wrap only part of your tree:
// <StrictMode><Sidebar /></StrictMode>useEffect) mount,
unmount, and re-mount in development. This exposes bugs in effects that don't
clean up properly — e.g. subscriptions, timers, and event listeners.componentWillMount, old string refs, findDOMNode, and the legacy Context API.
useEffect
fires twice on mount during development. This is intentional — it simulates a fast
refresh and unmount/remount cycle. If your effect breaks on second run, it means you're
missing a cleanup function. The solution is always to return a cleanup, never to remove
StrictMode.
7. React Portals — Render Outside the Root
By default, React renders everything inside the #root div.
Portals let you render a child component into a different DOM node
while keeping it logically inside the React tree. This is essential for
modals, tooltips, dropdowns,
and floating elements that need to escape the parent's CSS overflow, z-index,
or stacking context.
import { createPortal } from 'react-dom'
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null
return createPortal(
// 1st arg: JSX to render
<div className="modal-overlay" onClick={onClose}>
<div className="modal-box" onClick={e => e.stopPropagation()}>
{children}
<button onClick={onClose}>✕ Close</button>
</div>
</div>,
// 2nd arg: target DOM node (outside #root)
document.body
)
}
// index.html — no changes needed, body is already there
// The modal renders as a direct child of <body>
// but events still bubble up through the React tree ✅#root in the DOM,
React events still bubble through the React component tree, not the DOM tree.
A click inside the portal will bubble up to the component that rendered the Portal, giving you
full React event propagation as if the portal were in-place.
8. Hydration — SSR + React Takeover
Server-Side Rendering (SSR) sends pre-rendered HTML from the server so the browser can show content immediately — before any JavaScript loads. Once React's JS bundle loads, it hydrates the existing HTML: attaches event listeners, reconciles the Virtual DOM, and takes over interactivity — without re-rendering the page from scratch.
// index.html arrives empty: <div id="root"></div> // React builds the full DOM in the browser: // ✅ Simple setup (Vite default) // ❌ Blank screen until JS loads // ❌ Poor SEO for dynamic content // ❌ Slower First Contentful Paint createRoot(document.getElementById('root')) .render(<App />)
// index.html arrives pre-filled: <div id="root"><h1>Hello</h1>...</div> // React "hydrates" the existing HTML: // ✅ Fast First Contentful Paint // ✅ Great SEO // ✅ Works without JS (degraded) // ⚠️ More complex setup (Next.js) import { hydrateRoot } from 'react-dom/client' hydrateRoot(document.getElementById('root'),<App/>)
window-only values), React throws a
hydration mismatch error. Fix: use
suppressHydrationWarning on the specific element, or
render dynamic content inside a useEffect
(client-only after mount).
9. Performance Rules That Come From How Rendering Works
Now that you understand the render pipeline and diffing algorithm, these rules make perfect sense. Each one is directly derived from the mechanics above:
useEffect, not in the component body.React.memo() to skip re-renders when props don't
change.setState calls in event handlers, timeouts, and
promises into a single re-render. Avoid calling flushSync unless you truly need immediate DOM update.
style={{ color:'red' }}
creates a new object on every render — breaking React.memo. Move stable objects outside the component
or use useMemo.memo, useMemo, or useCallback. Premature optimisation adds complexity
with no benefit.Explore More Tutorials
The Virtual DOM is a lightweight plain JavaScript object that describes what the UI should look like. React builds a new Virtual DOM tree on every render (cheap — pure JS), then diffs it against the previous tree, and only applies the minimal set of real DOM mutations needed (the "patch").
React uses it because: (1) JavaScript object manipulation is orders of magnitude faster than DOM manipulation, (2) it enables batching multiple updates into a single DOM write, and (3) it makes React platform-agnostic (the same Virtual DOM can target the browser, mobile via React Native, or custom renderers).
By calling component functions twice, StrictMode detects impure renders: if the function has side effects (e.g., incrementing an external counter, directly mutating a variable), those side effects will happen twice and produce visible bugs in development — alerting you to fix them before they cause silent issues in production.
For effects (
useEffect), the double mount simulates
fast refresh. If your effect doesn't clean up properly, the second mount will fail or
behave incorrectly, alerting you to add a cleanup function. StrictMode has zero
effect in production.
#root container, while keeping it
logically inside the React component tree (events still bubble normally through React).
Use Portals when a component needs to visually break out of its parent's CSS constraints — specifically when the parent has
overflow: hidden,
a low z-index, or a CSS transform that creates a new
stacking context. The most common cases:
- Modals / dialogs that must appear above all other content
- Tooltips that shouldn't be clipped by
overflow:hiddenparents - Dropdown menus that need to escape a scrollable container
- Toast / notification systems
createRoot in React
18?useEffect fire?
<Login /> to <Dashboard />. What happens to
<Login />'s state?
createRoot and
hydrateRoot?
createRoot(container).render(<App />)is the React 18 entry point — enables Concurrent Mode and automatic batching.- The render pipeline has 4 phases: Trigger → Render (JS) → Commit (DOM) → Paint (browser).
- The Virtual DOM is a plain JavaScript object tree. React diffs new vs old to compute the minimal real DOM update.
- Reconciliation rules: same element type → update attributes; different type → destroy &
rebuild; use stable
keyprops for lists. - Re-render triggers:
setState, prop changes, context updates, parent re-renders. Block withReact.memo(). StrictModedouble-renders in dev to catch impure renders and missing effect cleanups — zero production cost, always keep it on.- Portals render into a different DOM node while preserving React event bubbling — essential for modals and tooltips.
hydrateRootattaches React to server-rendered HTML (SSR) without rebuilding the DOM — requires matching server/client output.- Performance rules: keep renders pure, place state low, use stable keys, batch updates, avoid inline objects as props, profile before optimising.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.