Appearance
Rendering and Performance
23. When does a React component re-render?
The short answer
A component re-renders when its own state changes, when a context it reads changes, or when its parent re-renders. The last one surprises people: by default, when a parent renders, every child renders too, even if its props did not change. Rendering means calling the function again and comparing results; it does not mean the DOM changes. Re-renders are usually cheap, and only become a problem when a large tree or an expensive component renders far more often than needed.
memo whose props are the same is skipped, along with its own children.The four triggers:
| Trigger | Example |
|---|---|
| Its own state changed | setQuery('tea') in a search box |
| Its parent re-rendered | The page component's state changed |
| A context it reads changed | The theme switched (question 18) |
| A subscribed external store changed | A Zustand or Redux slice it selects (question 45) |
Props changing is not on the list by itself. A child does not render because its props changed; it renders because its parent rendered, and the parent passes the props. Only memo makes "props unchanged" a reason to skip (question 24).
Render is not commit. React calls your function, compares the result with the previous one, and if nothing differs, the DOM is not touched (question 4). Many re-renders cost microseconds.
Cheap fixes that need no memoisation:
- Move state down. If only a search box uses
query, keepqueryinside the search box, not in the page, so typing does not re-render the whole page. - Pass children instead. A component that re-renders often can receive heavy parts as
children, which were created by a parent that did not re-render, so React reuses them.
tsx
function HoverCard({ children }: { children: React.ReactNode }) {
const [hovered, setHovered] = useState(false) // changes often
return (
<div onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}
className={hovered ? 'card lift' : 'card'}>
{children} {/* not re-rendered on hover */}
</div>
)
}24. What does React.memo do?
The short answer
memo(Component) makes React skip re-rendering that component when its parent re-renders, as long as every prop is the same as last time, compared with Object.is, which for objects and functions means the same reference. It is useful for components that are expensive to render and receive the same props most of the time. It only works if the parent passes stable props, so objects and callbacks usually need useMemo and useCallback, or the React Compiler.
tsx
const PriceChart = memo(function PriceChart({ points }: { points: number[] }) { // (1)
return <svg>{/* draws 2,000 points */}</svg>
})
function ProductPage({ productId }: { productId: string }) {
const [qty, setQty] = useState(1)
const history = usePriceHistory(productId) // (2)
return (
<>
<QuantityPicker value={qty} onChange={setQty} />
<PriceChart points={history} /> {/* (3) */}
</>
)
}- Wrapped in
memo. It re-renders only whenpointsis a different array. - The data comes from a hook that returns the same array until the data changes, for example from TanStack Query's cache.
- Changing the quantity re-renders
ProductPage, butPriceChartis skipped, becausehistoryis the same reference.
How memo is usually defeated:
tsx
<PriceChart points={history.map((p) => p.price)} /> // new array every render
<PriceChart points={history} onHover={() => {}} /> // new function every render
<PriceChart points={history} style={{ height: 200 }} /> // new object every renderEach creates a new reference on every render, so the props always look "changed" and memo does nothing except add a comparison. Wrap such values with useMemo or useCallback (question 17), or move constants outside the component.
When to use it: after measuring, on components that are slow to render and often receive the same props, such as charts, big tables, rows of a long list, or rich text editors. Wrapping everything in memo adds cost and noise.
A custom comparison can be passed as a second argument, but it is easy to get wrong, for example by forgetting a prop, which leaves the component showing stale data.
25. What is the React Compiler?
The short answer
The React Compiler is a build-time tool, a Babel plugin, that analyses your components and hooks and automatically memoises values, callbacks and JSX, so components skip work when their inputs have not changed. It replaces most hand-written useMemo, useCallback and memo. It became stable in late 2025. It relies on your code following the rules of React, such as pure rendering and not mutating props or state; code that breaks them is left as it is.
What it does for you:
tsx
// You write this
function OrderTotals({ orders, currency }: { orders: Order[]; currency: string }) {
const total = orders.reduce((s, o) => s + o.total, 0)
const formatted = new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(total)
return <Summary label="Total" value={formatted} />
}
// The compiler effectively produces code that recomputes `total`, `formatted` and the
// <Summary /> element only when `orders` or `currency` changes.Enabling it in a Vite project:
ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
react({ babel: { plugins: ['babel-plugin-react-compiler'] } }), // (1)
],
})- The compiler runs as a Babel plugin inside the React plugin. Next.js has a built-in option for it.
What you should still know:
| Point | Why |
|---|---|
| Rules of React matter more | The compiler assumes rendering is pure; mutating props or state during render breaks it |
useMemo and useCallback still work | Existing code keeps running; you can remove them gradually |
| It is not a fix for slow algorithms | Sorting 100,000 rows is still slow; it just avoids repeating it |
| Escape hatch | The 'use no memo' directive turns it off for one component |
In an interview, a good answer is: "Manual memoisation is a tool for specific measured problems; the React Compiler now automates most of it, so I focus on keeping components pure and state close to where it is used."
26. How do lazy loading and Suspense work?
The short answer
React.lazy(() => import('./AdminPage')) creates a component whose code is downloaded only the first time it renders, so the bundle for the first page is smaller. While the code loads, the component suspends, and the nearest <Suspense fallback={…}> boundary above it shows the fallback, such as a spinner. Suspense also works for data with libraries and frameworks that support it, so you write components as if the data were already there, and the boundary handles the loading state.
tsx
import { lazy, Suspense } from 'react'
import { Routes, Route } from 'react-router'
const AdminDashboard = lazy(() => import('./pages/AdminDashboard')) // (1)
const Reports = lazy(() => import('./pages/Reports'))
function App() {
return (
<Suspense fallback={<PageSpinner />}> {/* (2) */}
<Routes>
<Route path="/" element={<Home />} /> {/* (3) */}
<Route path="/admin" element={<AdminDashboard />} />
<Route path="/reports" element={<Reports />} />
</Routes>
</Suspense>
)
}- A lazy component. Vite turns each
import()into a separate file, a chunk, loaded on demand (question 59). - The boundary shows the fallback while any lazy component inside it is loading.
- Normal imports stay in the main bundle, so the home page appears quickly.
How suspending works, simply. When a lazy component renders before its code is loaded, it throws a special promise. React catches it at the nearest Suspense boundary, shows the fallback, and renders the component again when the promise resolves.
Where to put boundaries:
| Placement | Effect |
|---|---|
| One around the whole app | Any loading shows one full-page spinner |
| One per route | Navigation shows a spinner in the page area, header stays |
| Around slow widgets | The rest of the page shows; only the widget waits |
Avoid the waterfall. If the page waits for its code, then starts fetching its data, the user waits for both in turn. Start data requests early, for example with a router loader or queryClient.prefetchQuery (question 53), so code and data load in parallel.
Preloading on intent: call the import() when the user hovers over the "Reports" link, so the chunk is usually ready by the time they click.
27. What are useTransition and useDeferredValue for?
The short answer
They let React treat some updates as less urgent, so typing and clicking stay responsive while heavy rendering happens in the background. useTransition gives you startTransition to mark a state update as non-urgent and an isPending flag to show progress. useDeferredValue gives you a copy of a value that lags behind during heavy updates. If a more urgent update arrives, React abandons the in-progress background render and starts over with the latest data.
The problem: typing in a filter box that re-renders a list of 10,000 products. Each keystroke blocks the input while the list renders, so typing feels laggy.
tsx
function ProductSearch({ products }: { products: Product[] }) {
const [query, setQuery] = useState('')
const deferredQuery = useDeferredValue(query) // (1)
const isStale = query !== deferredQuery
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} /> {/* (2) */}
<div style={{ opacity: isStale ? 0.6 : 1 }}> {/* (3) */}
<ProductGrid products={products} query={deferredQuery} />
</div>
</>
)
}
const ProductGrid = memo(function ProductGrid({ products, query }: { products: Product[]; query: string }) {
const visible = products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase()))
return <ul>{visible.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
})- A deferred copy of
query. It updates after the urgent render, in the background. - The input uses the real
query, so every keystroke shows instantly. - The grid uses the deferred value, and is dimmed while it catches up.
memois needed so the grid is not re-rendered with the old value on every keystroke.
useTransition, for a tab switch that renders a heavy page:
tsx
const [isPending, startTransition] = useTransition()
function selectTab(tab: Tab) {
startTransition(() => setTab(tab)) // non-urgent: the old tab stays usable meanwhile
}useTransition | useDeferredValue | |
|---|---|---|
| You control | The state update | A value you receive |
| Use when | You own the setter | The value comes from props or another hook |
| Gives you | isPending | A lagging copy to compare |
These do not make work faster. They change priority, so the screen stays responsive. If filtering itself is slow, also reduce the work, for example with virtualisation (question 28).
28. How do you render a very long list efficiently?
The short answer
Render only the rows that are visible on screen, plus a few above and below, instead of all of them. This is called virtualisation or windowing: a container with the full scroll height is created, and as the user scrolls, the library swaps which rows are mounted. Libraries such as TanStack Virtual and react-window do this, turning 10,000 DOM nodes into about 20. Add stable keys, memoised rows and, where possible, pagination on the server.
tsx
import { useVirtualizer } from '@tanstack/react-virtual'
function OrderTable({ orders }: { orders: Order[] }) {
const parentRef = useRef<HTMLDivElement>(null)
const rows = useVirtualizer({
count: orders.length, // (1)
getScrollElement: () => parentRef.current,
estimateSize: () => 48, // (2)
overscan: 8, // (3)
})
return (
<div ref={parentRef} style={{ height: 600, overflow: 'auto' }}>
<div style={{ height: rows.getTotalSize(), position: 'relative' }}> {/* (4) */}
{rows.getVirtualItems().map((row) => (
<div key={orders[row.index].id}
style={{ position: 'absolute', top: 0, transform: `translateY(${row.start}px)`, height: row.size, width: '100%' }}>
<OrderRow order={orders[row.index]} /> {/* (5) */}
</div>
))}
</div>
</div>
)
}- The total number of rows in the data.
- An estimated row height, used to calculate scroll positions.
- A few extra rows above and below the visible area, so fast scrolling shows no gaps.
- A tall inner box makes the scroll bar behave as if every row existed.
- Only about 20 rows are mounted at any moment, each placed at its real position.
Other ways to cut the cost of long lists:
| Approach | When |
|---|---|
| Pagination or "load more" | Users rarely need all 10,000 at once |
| Infinite query from the server | Feeds, search results (question 52) |
| Virtualisation | Data must feel like one long scrollable list |
memo on rows | Rows re-render often for unrelated reasons |
CSS content-visibility: auto | Browser skips rendering work for off-screen sections |
29. How do you find and fix a slow React page?
The short answer
Measure before changing anything. Use the React DevTools Profiler to record an interaction and see which components rendered, how often and how long each took, and turn on "highlight updates" to spot unexpected re-renders. Use the browser's Performance panel to find long tasks, and check network waterfalls and bundle size separately. Then fix the real cause: move state down, split contexts, memoise the expensive component, virtualise long lists, lazy-load heavy code, or fix slow data fetching.
A practical routine:
- Reproduce it with a production build,
vite build && vite preview, because development mode is much slower and double-renders (question 10). - Classify the slowness:
| Symptom | Look at | Likely cause |
|---|---|---|
| Slow first load | Network panel, bundle analyser | Big JavaScript bundle, waterfalls, unoptimised images |
| Typing or clicking lags | React Profiler, Performance panel | Too many or too expensive re-renders |
| Scrolling stutters | Performance panel | Too many DOM nodes, heavy layout |
| Spinner for a long time | Network panel | Slow API, sequential requests |
- Record with the Profiler. The flame chart shows each component's render time; the "why did this render" setting names the prop, state or context that changed.
- Fix the biggest item first, and measure again.
Fixes matched to causes:
| Cause | Fix |
|---|---|
| State too high, a page re-renders on each keystroke | Move state into the component that uses it (question 23) |
| One context with everything in it | Split it, or use a store with selectors (question 40) |
| One slow component re-rendering with the same props | memo, with stable props, or the React Compiler (question 24) |
| 5,000 rows in the DOM | Virtualise (question 28) |
| Heavy library on a page few people visit | lazy and import() (question 26) |
| Requests one after another | Start them in parallel, prefetch (question 53) |
| Heavy computation during render | useMemo, a web worker, or do it on the server |
Measure what users feel. Core Web Vitals, collected from real users, show whether the fix helped: Largest Contentful Paint for loading, Interaction to Next Paint for responsiveness, and Cumulative Layout Shift for visual stability.