Portals, error boundaries, Suspense and lazy
Three tools for real-world UI problems: portals render a modal outside its parent's DOM so it is not clipped, error boundaries stop one render error from blanking the whole app, and lazy + Suspense split heavy code into separate chunks that load only when needed.
40.1 Problem: modal clipped inside the card
- ProductCard has an open state; clicking Details renders a Modal whose overlay should cover the whole screen.
- The card CSS has overflow: hidden (rounded corners) and a transform (hover animation).
- Result: the modal is clipped inside the card.
import { useState } from "react";import Modal from "./Modal";export default function ProductCard() { const [open, setOpen] = useState(false); return ( <div className="card"> <button onClick={() => setOpen(true)}> Details </button> {open && ( <Modal onClose={() => setOpen(false)} /> )} </div> );}[button] Details-- click Details --Modal clipped inside the card40.2 Why was the modal clipped?
- The modal's HTML is created inside the card in the DOM, so the card's overflow: hidden clips it.
- Because of the transform, even position: fixed is measured from the card, not the viewport.
- The problem is not React but where the modal lives in the DOM: we want the component inside the card, its HTML inside body.
40.3 Fix: createPortal
- Import createPortal from react-dom; Modal passes its JSX to createPortal with document.body as the second argument.
- In the React tree Modal is still a child of ProductCard, but its HTML renders inside body, so the overlay covers the whole screen.
- Click events inside a portal still bubble up to ProductCard, following the React tree, not the DOM tree.
import { createPortal } from "react-dom"; export default function Modal({ onClose }) { return createPortal( <div className="overlay"> <div className="dialog"> <p>Order #1024 details</p> <button onClick={onClose}>Close</button> </div> </div>, document.body );}-- click Details --Overlay: covers the whole screenOrder #1024 details[button] Close- Step 1
1.ProductCard renders <Modal /> (React child of the card)
- Step 2
2.Modal returns createPortal(jsx, document.body)
- Step 3
3.React mounts the overlay HTML directly under <body>
- Step 4
4.Card's overflow: hidden and transform no longer apply
- Step 5
5.Clicks inside still bubble to ProductCard via the React tree
React tree stays the same, DOM location changes
40.4 Problem: one error, whole app white
- PriceTag calls product.price.toFixed(2), but the API product has no price field: TypeError.
- When a render error is not caught, React unmounts the whole root.
- The heading and the Add to cart button are gone too: the user sees a blank white screen.
function PriceTag({ product }) { return <p>₹{product.price.toFixed(2)}</p>;} export default function App() { const product = { name: "Shoes" }; return ( <main> <h1>My Shop</h1> <PriceTag product={product} /> <button>Add to cart</button> </main> );}Screen: blank white pageConsole: TypeError: Cannot read properties of undefined (reading 'toFixed')40.5 Fix: an ErrorBoundary class
- An error boundary is a component that catches render errors in its children.
- It is still a class component: React has no hook for this.
- static getDerivedStateFromError sets hasError to true as soon as an error happens.
- componentDidCatch logs the error or sends it to a reporting service.
- render shows the fallback if hasError, otherwise the normal children.
import { Component } from "react"; export default class ErrorBoundary extends Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error) { console.log("Report:", error.message); } render() { if (this.state.hasError) return this.props.fallback; return this.props.children; }}40.6 A fallback for one section only
- Wrap only PriceTag in ErrorBoundary with fallback={<p>No price</p>}.
- The same error now shows only "No price" in place of PriceTag; the heading and Add to cart keep working.
- The Report message from componentDidCatch can go to a tool like Sentry in a real project.
import ErrorBoundary from "./ErrorBoundary";import PriceTag from "./PriceTag"; export default function App() { const product = { name: "Shoes" }; return ( <main> <h1>My Shop</h1> <ErrorBoundary fallback={<p>No price</p>}> <PriceTag product={product} /> </ErrorBoundary> <button>Add to cart</button> </main> );}# My ShopNo price[button] Add to cartConsole: Report: Cannot read properties of undefined (reading 'toFixed')- Step 1
1.PriceTag throws TypeError during render
- Step 2
2.React looks up for the nearest ErrorBoundary
- Step 3
3.getDerivedStateFromError -> { hasError: true }
- Step 4
4.componentDidCatch logs / reports the error
- Step 5
5.Boundary renders fallback; rest of the app keeps working
No boundary? React unmounts the whole root
40.7 Checkpoint: event handler errors
- BuyButton's click handler throws, and the button sits inside ErrorBoundary.
- Clicking Buy shows no fallback: error boundaries catch only render errors.
- The handler error appears in the console as an Uncaught Error; use a normal try/catch in event handlers.
import ErrorBoundary from "./ErrorBoundary";function BuyButton() { function pay() { throw new Error("Payment failed"); } return <button onClick={pay}>Buy</button>;} export default function App() { return ( <ErrorBoundary fallback={<p>Oops</p>}> <BuyButton /> </ErrorBoundary> );}Screen: Buy button same, no OopsUncaught Error: Payment failed| Error happens in | Caught by an error boundary? | What to use instead |
|---|---|---|
| Render of a child component | Yes | - |
| Event handler (onClick) | No | try/catch in the handler |
| Async code (setTimeout, promises) | No | try/catch / .catch() |
| Server rendering (SSR) | No | Server-side error handling |
| The boundary itself | No | A boundary higher up |
40.8 Code splitting: lazy + Suspense
- By default the build puts all code in one big JavaScript bundle, so a heavy chart the user has not opened is downloaded upfront.
- lazy(() => import("./Chart")) loads Chart with a dynamic import; the build tool puts it in a separate chunk.
- The Suspense fallback shows Loading... while the chunk downloads, then the Monthly sales chart appears.
import { lazy, Suspense } from "react"; const Chart = lazy(() => import("./Chart")); export default function Dashboard() { return ( <main> <h1>Dashboard</h1> <Suspense fallback={<p>Loading...</p>}> <Chart /> </Suspense> </main> );}# DashboardLoading...-- chunk downloaded --# DashboardMonthly sales chart- Step 1
1.Build: Chart goes into its own chunk
- Step 2
2.Page opens: only the small main bundle downloads
- Step 3
3.Chart needs to render: its chunk downloads, Suspense shows the fallback
- Step 4
4.Chunk ready: the real chart replaces Loading...
40.9 Common mistakes
- Calling lazy inside the component: a new Chart component every render, React suspends again and the screen stays stuck on Loading.
- Fix: always declare lazy at the top level of the file, outside the component.
// Wrong: new Chart every render -> stuck on Loadingexport default function Dashboard() { const Chart = lazy(() => import("./Chart")); return <Chart />;}// Right: top level -> Chart created onceconst Chart = lazy(() => import("./Chart")); export default function Dashboard() { return <Chart />;}- Myth: "make everything lazy and the app gets fast". Every lazy component adds a network request and a loading state; splitting small components can feel slower.
- Use lazy for routes, heavy libraries (charts, editors) and rarely opened modals.
- Only one error boundary around the whole app: one error still blanks everything inside it.
40.10 Simple rules
- Render modals, tooltips and toasts into body with a portal.
- Give each important section its own error boundary; real projects also use the react-error-boundary library.
- Declare lazy at the top level and give Suspense a fallback that clearly says something is loading.
40.11 Interview tips
- An error boundary is a class component that catches render errors in its children and shows a fallback UI.
- getDerivedStateFromError shows the fallback; componentDidCatch logs the error.
- It does not catch errors from event handlers, async code like setTimeout, or server rendering.
- A portal changes only the DOM location; events still bubble through the React tree. lazy + Suspense = code splitting.