Tutorials React JS Rendering & ReactDOM
Ch 5 / 46
Chapter 5 Beginner 12 min read React JS

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.

Advertisement
What you'll learn
ReactDOM & createRoot — the entry point of every React app
The render pipeline — trigger → render → commit → paint
Virtual DOM — what it is and why React uses it
Reconciliation & diffing — how React minimises DOM updates
Render triggers — state changes, prop changes, context, forced re-renders
React.StrictMode — what double-invoking means and why it matters
Portals — rendering outside the root DOM node
Hydration — SSR HTML + React takeover explained

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.

React 17 — Legacy render (deprecated)
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
React 18 — createRoot (current)
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
jsx — src/main.jsx · complete annotated entry point
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 tree
react-dom/client
The sub-path react-dom/client contains the browser-specific APIs. The old react-dom import still works for legacy APIs like flushSync.
React 18+
Concurrent Mode
createRoot opts your app into Concurrent Mode — React can interrupt, pause, and resume rendering work, enabling Suspense and Transitions.
Performance
One root per app
You call createRoot() once per application. React manages the entire component tree from that single root — you never call it again after init.
Convention
Multiple roots
You can call createRoot() on multiple DOM nodes to embed React inside existing non-React pages. Each root is independent.
Advanced
Advertisement

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:

1
Trigger
Something causes React to re-render — a setState call, prop change, context update, or the initial root.render().
External event
→
2
Render
React calls your component functions to produce a new Virtual DOM tree (tree of React elements). This is pure JavaScript — no browser involvement yet.
JS only
→
3
Commit
React diffs the new Virtual DOM against the previous one and applies only the minimal set of real DOM changes needed. Runs useEffect cleanup here.
DOM write
→
4
Paint
The browser re-paints the screen with the updated DOM. React fires useEffect callbacks after the browser paints, so they don't block the UI.
Browser
Render ≠ Paint "Render" in React means calling your component functions to generate a Virtual DOM description. It does not mean updating the browser. React renders many times without painting (e.g., StrictMode double-renders). The browser only updates during the Commit phase — and only the parts that actually changed.

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.

js — what a Virtual DOM node (React element) looks like internally
// 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:

Before (count = 5)
<div className="card">
<h2> Hello React
<p> Count: 5 old
→
After (count = 6)
<div className="card"> unchanged
<h2> Hello React unchanged
<p> Count: 6 patched ✓
Unchanged — skipped
Changed — DOM patched
Removed — DOM node deleted
⭐⭐⭐⭐⭐
4.9 / 5
🔥 Most Popular at K2infocom · Vadodara
React JS Complete
Masterclass
Go from Virtual DOM fundamentals to full-stack React apps. Hooks, State, Context, Router, Redux, REST APIs & 6 real-world projects — all in one guided course.
Rendering & DOM Hooks & State React Router Redux Toolkit REST APIs 6 Projects Certificate
2,500+Students
6+Projects
3–6Months
100%Placement

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:

Assumption 1 — Element type
If two elements have different types (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.
Core rule
Assumption 2 — Keys for lists
For lists, React uses the key prop to match children across renders. Stable unique keys let React reorder, insert and remove items without re-mounting everything.
List optimisation
Assumption 3 — Component identity
If the same component type renders at the same position, React preserves its state. If the component type changes at a position, state is lost (the component is unmounted and remounted).
State preservation
Bail-out early
Components wrapped in React.memo() or PureComponent skip re-rendering if their props haven't changed — React bails out of the render phase entirely.
Optimisation

Type change destroys state — a common gotcha

❌ Type changes — state lost!
// 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 type — state preserved
// Same component type <Panel />
// React reuses the DOM node
// and updates props only.
// State inside Panel is preserved!

<Panel
  isAdmin={isLoggedIn}
/>
Force reset state with key You can intentionally reset a component's state by giving it a different 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.
Advertisement

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.

jsx — StrictMode wraps your entire app in main.jsx
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>
Double-invoking renders
StrictMode calls your component function twice in development. This catches components with side-effects in the render body — renders must be pure (same input → same output, no side effects).
Dev only
Double useEffect
Effects (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.
Bug detection
Deprecated API warnings
StrictMode logs warnings for deprecated lifecycle methods like componentWillMount, old string refs, findDOMNode, and the legacy Context API.
Migration aid
Zero prod cost
StrictMode behaviours (double renders, double effects) are completely stripped out of production builds. Always keep StrictMode on in new projects — it catches real bugs.
Safe to keep
"Why did my effect run twice?" The most common StrictMode confusion: your 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.

jsx — Modal component using createPortal
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 ✅
Portals & event bubbling Even though a Portal renders outside #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.

CSR (createRoot) — Client rendering
// 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 />)
SSR + Hydration (Next.js)
// 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/>)
Hydration mismatch error If the HTML React receives from the server doesn't match what React would render on the client (e.g., timestamps, 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:

Keep renders pure
Component functions must be pure — same props → same JSX output, no side effects during render. Side effects go in useEffect, not in the component body.
Rule #1
State low, memo high
Place state as low in the tree as possible (minimises re-render scope). Wrap expensive or stable children in React.memo() to skip re-renders when props don't change.
Rule #2
Stable keys in lists
Use stable database IDs as list keys. Unstable keys (e.g., Math.random() in render) cause React to unmount and remount every list item on every render — destroying state and causing flicker.
Rule #3
Batch state updates
React 18 automatically batches multiple setState calls in event handlers, timeouts, and promises into a single re-render. Avoid calling flushSync unless you truly need immediate DOM update.
Rule #4
Avoid inline objects/arrays as props
style={{ color:'red' }} creates a new object on every render — breaking React.memo. Move stable objects outside the component or use useMemo.
Rule #5
Profile before optimising
Use React DevTools Profiler to find actual slow renders before reaching for memo, useMemo, or useCallback. Premature optimisation adds complexity with no benefit.
Rule #6
Explore Rendering in Your Browser
Open React DevTools Profiler in Chrome, add a counter to any React app, and watch exactly which components re-render on each state change.
Open Vite + React on StackBlitz
Advertisement
Quick Check — Test Your Understanding
Q1. What is the difference between the Virtual DOM and the real DOM? Why does React use it?
✅ Answer
The real DOM is the browser's live representation of the page — updating it triggers layout recalculation, reflow, and repaint, which are expensive operations.

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).
Q2. Why does React.StrictMode invoke component functions and effects twice in development?
✅ Answer
React's rule is that component renders must be pure — the same props/state always produce the same output, with no side effects during the render phase.

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.
Q3. What is a React Portal and when would you use one?
✅ Answer
A Portal renders a React component's output into a different DOM node outside the #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:hidden parents
  • Dropdown menus that need to escape a scrollable container
  • Toast / notification systems
Multiple Choice Questions
MCQ 1
What is the correct import path for createRoot in React 18?
MCQ 2
In the React render pipeline, when does useEffect fire?
MCQ 3
You change the component type at a given position from <Login /> to <Dashboard />. What happens to <Login />'s state?
MCQ 4
What is the primary difference between createRoot and hydrateRoot?
Chapter 5 Summary
  • 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 key props for lists.
  • Re-render triggers: setState, prop changes, context updates, parent re-renders. Block with React.memo().
  • StrictMode double-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.
  • hydrateRoot attaches 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel