Questions 121–140 of 150 · 0 of 20 on this page marked learned
121.react-0121Mediummid
What is automatic batching in React 18, how did batching work before it, and how do you opt out with flushSync?
Batching groups several state updates into one re-render. Before React 18, React batched updates only inside React event handlers, so updates in timeouts, promises and native event handlers caused one render per setState. React 18 with createRoot batches all updates automatically, wherever they happen, within the same tick. To force a synchronous render for one update, wrap it in flushSync from react-dom, and use it rarely.
Full answer
A render is not free, so React avoids rendering after every setState. When several updates happen together, React waits and applies them in one pass.
React 17 and earlier. React batched only updates that ran inside its own event handlers. Inside the handler, setA(1); setB(2) gave one render. In a setTimeout, a fetch().then, or a native addEventListener callback, each setter caused its own synchronous re-render, so two updates rendered twice, and in between the UI could show half-updated state. Developers used ReactDOM.unstable_batchedUpdates to work around it.
React 18. With createRoot, all updates are batched automatically, whatever their origin: handlers, timeouts, promises, native events. The updates scheduled in the same tick lead to a single render. Apps that still use the legacy ReactDOM.render API (removed in React 19) keep the old behaviour, which is part of why migrating to createRoot matters.
Opting out. Rarely you need the DOM to be updated immediately between two updates, for example to measure the layout after the first. flushSync(() => setA(1)) from react-dom forces React to apply that update synchronously, then the following updates are handled separately. It can hurt performance and may flush pending effects, so treat it as an escape hatch.
Related ideas: updates inside a transition are batched and lower priority, setState with the updater form queues operations in order, and batching never changes the final state, only the number of renders.
The example counts renders after two updates in a timer, with and without flushSync.
jsx
import { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { createRoot } from 'react-dom/client';
let api;
let renders = 0;
function Counter() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
renders += 1;
useEffect(() => {
api = { setA, setB };
}, []);
return (
<p>
a={a}, b={b}
</p>
);
}
const container = document.getElementById('root');
createRoot(container).render(<Counter />);
const wait = () => new Promise((resolve) => setTimeout(resolve, 30));
await wait();
let before = renders;
setTimeout(() => {
api.setA(1);
api.setB(1);
});
await wait();
console.log('two updates in a timer: ' + (renders - before) + ' render(s)');
before = renders;
setTimeout(() => {
flushSync(() => api.setA(2));
api.setB(2);
});
await wait();
console.log('with flushSync around the first: ' + (renders - before) + ' render(s)');
console.log('final output: ' + container.textContent);
This ran as a script with React 19 and createRoot. The counter increments a module variable during render, which is acceptable only for a demo. Two updates in a timer rendered once, and flushSync made the first update render on its own. Output of the run:
two updates in a timer: 1 render(s)
with flushSync around the first: 2 render(s)
final output: a=2, b=2
Key points
Batching groups multiple state updates into one render.
Before React 18, only updates in React event handlers were batched.
With createRoot in React 18 and later, all updates are batched automatically.
flushSync forces a synchronous render for the update inside it. Use it sparingly.
Batching changes the number of renders, not the final state.
Common mistakes
Assuming each setState call causes a render.
Using unstable_batchedUpdates in React 18 and later code.
Calling flushSync often and losing the performance benefit.
Expecting legacy ReactDOM.render apps to batch automatically.
Counting renders inside a component without Strict Mode in mind, which doubles them in development.
Follow-ups
Why does a legacy-root app not get automatic batching?
How does batching interact with transitions?
Which situations really need flushSync?
Tips
Tell the history in two steps: handlers only, then everything.
Say flushSync is an escape hatch with a cost.
Mention that batching changes render count, not the final result.
122.react-0122Mediummid
What is structural sharing, and how do immutable updates help React skip work?
Structural sharing means that when you create a new version of a nested object, you copy only the path to the changed value and reuse (share) every unchanged branch. Reused branches keep the same reference, so React can skip them with a cheap equality check (memo, dependency arrays, selectors). Spread syntax does this by hand, and libraries such as Immer do it automatically. Mutation breaks it, because the reference is unchanged although the content changed.
Full answer
React compares values by reference (Object.is) to decide whether things changed: props in memo, dependencies in useEffect and useMemo, and selectors in stores. This only works if you never mutate objects in place and always create a new object when something inside changes.
Copying everything on each update would be expensive and would defeat memoization, because every branch would get a new identity. Structural sharing solves both. An update such as "rename the student" creates a new root object and a new student object (the path to the change), but the courses array and the address object, which did not change, are reused. Their references are identical to the previous state, so components that only depend on them can skip rendering.
By hand with spread: { ...state, student: { ...state.student, name: 'Meera' } }. This is correct and explicit, but deeply nested updates become verbose and easy to get wrong.
With Immer, used inside Redux Toolkit's createSlice, you write the update as if you were mutating a draft (draft.student.name = 'Meera'), and Immer produces the new immutable state with structural sharing. It records only the touched paths and reuses the rest. If nothing changes, it returns the same state object. Immer also freezes the result in development to catch accidental later mutation.
Implications. Selectors that return the same reference for unchanged data let useSelector avoid re-renders. memo children with unchanged object props are skipped. Time-travel debugging and undo become easy because old versions remain intact. The cost is allocation and a different way of thinking, which is small compared with the rendering work it saves.
Pitfalls: mutating nested objects after copying only the top level (shallow copy), using JSON.parse(JSON.stringify(x)) for deep clones (this destroys sharing and makes every branch new), and copying large arrays on every keystroke without need.
The example shows that unchanged branches keep their identity.
This ran as a script with the Immer library, the same one that Redux Toolkit uses inside createSlice. Output of the run:
spread: student is new: true
spread: courses is shared: true
spread: address is shared: true
immer: student is new: true
immer: courses is shared: true
immer: address is shared: true
immer: original untouched: Asha
immer with no changes returns the same object: true
JSON clone shares courses: false
Key points
React skips work by comparing references, so updates must create new objects instead of mutating.
Structural sharing copies only the changed path and reuses unchanged branches.
Spread syntax does it by hand. Immer does it automatically from mutation-style code.
Unchanged references let memo, selectors and dependency arrays skip work.
Deep cloning with JSON destroys sharing and should be avoided.
Common mistakes
Copying only the top level and mutating nested objects.
Deep cloning with JSON for every update.
Mutating state and expecting memoized components to update.
Creating new arrays or objects for data that did not change.
Expecting Immer drafts to work outside the produce callback.
Follow-ups
How does Immer know which parts of the state were changed?
Why do selectors depend on stable references?
When would you avoid Immer and write spread updates?
Tips
Define structural sharing in one sentence before showing code.
Connect it to memo and selector behaviour.
Warn against JSON deep clones.
123.react-0123Mediummid
How do you decide where to place Suspense boundaries, and how does placement change what users see while data loads?
A Suspense boundary shows its fallback until every suspended component inside it is ready, and then reveals everything inside together. One boundary around a whole page makes users wait for the slowest part. Separate boundaries around independent sections let each part appear as soon as its data arrives. Place boundaries at meaningful UI units, keep layout stable with fallbacks of similar size, and nest them to get progressive reveal without too many spinners.
Full answer
When a component suspends (it reads a promise with use, or loads lazy code), React looks upward for the nearest <Suspense> boundary and shows its fallback in place of that whole boundary's content. When all components inside are ready, they appear together.
Placement decides the experience:
One boundary around the page: simple, but the page stays in the fallback until the slowest request finishes. This is a "loading spinner for everything" design.
A boundary per independent section (profile, posts, recommendations): the fast sections appear first and the slow one shows its own fallback. Users read content sooner.
Nested boundaries: an outer boundary for the layout and an inner one for slow details. React reveals outer content when it is ready, then inner content later.
Guidelines:
Put a boundary where a loading placeholder makes sense visually (a card, a list, a sidebar), not around tiny elements.
Use fallbacks (skeletons) with similar dimensions to the content to prevent layout shift.
Do not create so many boundaries that the page "pops" in dozens of times. Group parts that should appear together.
Fetch in parallel: start all promises before rendering (route loader, parent), because sibling components that suspend one after another in the same boundary create a waterfall.
Use transitions for updates. When already visible content would suspend again, startTransition keeps the old content on screen instead of showing the fallback again.
Pair every boundary with an error boundary decision, because a rejected promise throws to the nearest error boundary.
With streaming server rendering the same boundaries decide what HTML is sent first and what streams later.
The example renders the same two data sources (fast and slow) with one shared boundary and with separate boundaries.
The two promises are created when the module loads, only to keep the demo small. In a real app they would come from a loader or a cache. The check looked at the page at the start, after the fast request, and after the slow one. Output of the run:
early => one shared boundary: Loading everything... || separate boundaries: Loading profile...Loading posts...
after the fast request => one shared boundary: Loading everything... || separate boundaries: Profile: AshaLoading posts...
after the slow request => one shared boundary: Profile: AshaPosts: 2 new || separate boundaries: Profile: AshaPosts: 2 new
Key points
A boundary shows its fallback until all suspended parts inside are ready, then reveals them together.
One page-wide boundary waits for the slowest data. Separate boundaries reveal sections progressively.
Place boundaries at meaningful UI units and size the fallbacks like the content.
Start data requests in parallel to avoid waterfalls inside a boundary.
Use transitions to avoid hiding visible content again, and add error boundaries.
Common mistakes
Wrapping the entire app in one boundary and showing a full-page spinner for every load.
Creating the promise inside the component that uses it.
Using fallbacks with a different size from the content, causing layout shift.
Adding a boundary around every small element.
Forgetting an error boundary for rejected promises.
Follow-ups
How do transitions prevent a fallback from showing again?
How do Suspense boundaries influence streaming server rendering?
How would you avoid a waterfall between two sibling components that both fetch?
Tips
Describe the "slowest part" problem of a single boundary.
Mention fallback size and layout shift.
Link boundaries to transitions and error boundaries.
124.react-0124Mediummid
Compare CSR, SSR, SSG, ISR and React Server Components. When would you use each?
CSR sends an empty shell and renders in the browser. SSR renders HTML on the server for each request. SSG renders HTML once at build time. ISR serves static HTML and regenerates it in the background after a time or on demand. Server Components render on the server and send a serialized result with no component JavaScript to the client, and can combine with any of the others. Choose by how fresh and personalized the data is, SEO needs and server cost.
Full answer
These terms describe where and when the HTML is produced.
Client-side rendering (CSR). The server returns a nearly empty HTML file and a JavaScript bundle. The browser runs React and fetches data, then draws the UI. Simple hosting (any static host), great for logged-in dashboards, but the first paint is later and search engines see little unless they execute JavaScript.
Server-side rendering (SSR). For each request the server runs React and returns complete HTML, followed by hydration in the browser. Good for SEO and fast first content with personalized or frequently changing data. It costs server compute and a time to first byte that depends on data fetching. Streaming improves it.
Static site generation (SSG). HTML pages are generated at build time and served from a CDN. Fastest and cheapest, ideal for content that changes rarely (docs, marketing, blogs). Content is fixed until the next build.
Incremental static regeneration (ISR). SSG with updates: a page is served from cache and regenerated in the background after a revalidate time or when you trigger it on demand. It scales a catalog of thousands of pages without full rebuilds. The data may be briefly stale.
React Server Components (RSC). A component model, not a delivery strategy by itself. Server Components run only on the server (at build time or per request), can read data directly, and add no JavaScript to the bundle. The client receives a serialized description to merge with Client Components. A framework such as Next.js combines RSC with static, dynamic and cached rendering per route.
Choosing: dashboards behind login: CSR or SSR with RSC. Marketing and docs: SSG. Large catalog with updates: ISR or cached RSC. Personalized, SEO-relevant pages: SSR (streaming). Modern frameworks let you pick per route, and newer versions use "static shell plus dynamic holes" ideas (partial prerendering), so name the trade-offs, not only the acronyms.
The example shows what the browser receives for each approach, and a small cache that regenerates after a time limit.
jsx
import { renderToString } from 'react-dom/server';
function CoursePage({ title, generatedAt }) {
return (
<main>
<h1>{title}</h1>
<p>Generated at tick {generatedAt}</p>
</main>
);
}
// CSR: the server sends an empty shell, and the browser fills it in.
console.log('CSR first HTML: ' + '<div id="root"></div>');
// SSR: HTML is rendered for each request.
let tick = 0;
const ssr = () => renderToString(<CoursePage title="React Basics" generatedAt={++tick} />);
console.log('SSR request 1: ' + ssr());
console.log('SSR request 2: ' + ssr());
// SSG: HTML is rendered once at build time and reused.
const built = renderToString(<CoursePage title="React Basics" generatedAt={++tick} />);
console.log('SSG request 1: ' + built);
console.log('SSG request 2: ' + built);
// ISR: serve the cached page, and regenerate when it is older than the revalidate time.
let cached = { html: built, createdAt: 0 };
function isr(now, revalidate) {
const stale = now - cached.createdAt >= revalidate;
const served = cached.html;
if (stale) cached = { html: renderToString(<CoursePage title="React Basics" generatedAt={++tick} />), createdAt: now };
return (stale ? 'served stale, regenerated: ' : 'served from cache: ') + served;
}
console.log('ISR at t=5: ' + isr(5, 10));
console.log('ISR at t=12: ' + isr(12, 10));
console.log('ISR at t=13: ' + isr(13, 10));
This ran as a script. The tick counter stands in for "data fetched at that moment". ISR is simulated with a small cache and not a real framework. The SSG page is the same string on every request. Server Components are not shown here, because they need a framework or bundler support. Output of the run:
CSR first HTML: <div id="root"></div>
SSR request 1: <main><h1>React Basics</h1><p>Generated at tick <!-- -->1</p></main>
SSR request 2: <main><h1>React Basics</h1><p>Generated at tick <!-- -->2</p></main>
SSG request 1: <main><h1>React Basics</h1><p>Generated at tick <!-- -->3</p></main>
SSG request 2: <main><h1>React Basics</h1><p>Generated at tick <!-- -->3</p></main>
ISR at t=5: served from cache: <main><h1>React Basics</h1><p>Generated at tick <!-- -->3</p></main>
ISR at t=12: served stale, regenerated: <main><h1>React Basics</h1><p>Generated at tick <!-- -->3</p></main>
ISR at t=13: served from cache: <main><h1>React Basics</h1><p>Generated at tick <!-- -->4</p></main>
Key points
CSR renders in the browser, SSR on each request, SSG at build time, ISR regenerates static pages over time.
Server Components add no client JavaScript for server-only parts and combine with the other strategies.
CSR fits logged-in apps. SSG fits stable content. SSR fits fresh or personalized SEO pages.
ISR trades freshness for scale, with time-based or on-demand regeneration.
Frameworks mix strategies per route. Explain trade-offs, not only definitions.
Common mistakes
Treating RSC, SSR and SSG as competing options when they combine.
Using SSR for content that never changes, paying server cost for nothing.
Using CSR for public pages that need search indexing.
Forgetting that ISR data can be stale for up to the revalidate time.
Naming acronyms without trade-offs.
Follow-ups
How does streaming change the cost of SSR?
How would you trigger on-demand revalidation after a content edit?
Where do Server Components fit in an SSG site?
Tips
Define each by "where and when HTML is produced".
Say RSC is orthogonal to the others.
Pick by data freshness, personalization and SEO.
125.react-0125Mediummid
Is React bad for SEO, and how do you make a React site search-engine friendly?
React is not bad for SEO, but a client-rendered SPA starts with empty HTML, so crawlers must run JavaScript, which is slower and less reliable, and link previews from social sites usually do not run scripts. Make the important content available in the initial HTML with server rendering or static generation, give each page a unique URL, title, description and canonical link, use semantic HTML and fast Core Web Vitals, and provide a sitemap. React 19 supports title, meta and link tags directly in components.
Full answer
Search engines index what they can see. Googlebot can execute JavaScript, but rendering happens in a second step that may be delayed, and other crawlers and social preview bots (Open Graph for chat apps and social posts) often read only the initial HTML. A pure CSR app returns <div id="root"></div>, so these tools see nothing.
What to do:
Put content in the first HTML response. Use SSR, SSG or ISR through a framework such as Next.js or React Router framework mode. Streaming works too.
One URL per piece of content. Use real paths (History API) and not only state or hash fragments. Make sure the server returns 200 for real pages and a true 404 status for missing ones, not a 200 with an error screen.
Per-page metadata. Each page needs a unique <title>, description, canonical URL and Open Graph tags. In React 19 you can render <title>, <meta> and <link> inside any component and React hoists them to the document head. Frameworks also provide metadata APIs.
Crawlable links. Use real <a href> elements for navigation, not click handlers on divs.
Semantic structure. One h1, ordered headings, lists, alt text. This helps both crawlers and accessibility.
Performance. Core Web Vitals influence ranking signals and user experience. Optimize LCP and layout shift.
Discovery files. sitemap.xml, robots.txt, and structured data (JSON-LD) for rich results.
Do not hide important content behind interactions that require clicks or infinite scroll without URLs (provide paginated URLs).
Verify with the "view source" page, Google Search Console's URL inspection, and a crawler that does not run JavaScript.
When a logged-in app has no SEO needs (a dashboard), CSR is fine. For public marketing and content, choose server-rendered output.
The example renders a document with page-level metadata and shows the resulting head.
jsx
import { renderToString } from 'react-dom/server';
function CoursePage({ course }) {
return (
<article>
<title>{course.title + ' | Schoolabe'}</title>
<meta name="description" content={course.summary} />
<link rel="canonical" href={'https://example.com/courses/' + course.slug} />
<h1>{course.title}</h1>
<p>{course.summary}</p>
<a href="/courses">All courses</a>
</article>
);
}
function Document({ children }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
</head>
<body>{children}</body>
</html>
);
}
const course = { title: 'React Basics', slug: 'react-basics', summary: 'Learn components, props and state.' };
const html = renderToString(
<Document>
<CoursePage course={course} />
</Document>
);
const head = html.match(/<head>([\s\S]*?)<\/head>/)[1];
console.log('head: ' + head);
console.log('h1 is in the first HTML: ' + html.includes('<h1>React Basics</h1>'));
This ran as a script with renderToString. The title, meta and link tags were written inside the page component, and React placed them in the head of the document. The search engine behaviour itself was not tested. Output of the run:
head: <meta charSet="utf-8"/><title>React Basics | Schoolabe</title><meta name="description" content="Learn components, props and state."/><link rel="canonical" href="https://example.com/courses/react-basics"/>
h1 is in the first HTML: true
Key points
A CSR app sends empty HTML. Crawlers and link previews may not run JavaScript, so content can be missed.
Render important content on the server (SSR, SSG, ISR) so it is in the first HTML.
Give each page a real URL, a unique title, description and canonical link, and return correct status codes.
React 19 hoists title, meta and link tags from components into the head.
Use semantic HTML, real links, a sitemap and good Core Web Vitals. Verify with view source.
Common mistakes
Shipping an empty HTML shell for public content pages.
Using click handlers on divs instead of links.
Returning status 200 for pages that do not exist.
Using the same title and description on every route.
Hiding content behind infinite scroll with no paginated URLs.
Follow-ups
How would you check what a crawler sees on a page?
How do you handle metadata in Next.js or React Router?
Why do social link previews often fail for client-rendered apps?
Tips
Say "React is fine, the rendering strategy decides".
Mention status codes and unique URLs, not only SSR.
Name a way to verify, such as view source and Search Console.
126.react-0126Mediummid
What are Core Web Vitals (LCP, CLS, INP), and what do you do in a React app to improve each one?
LCP measures how quickly the largest visible content appears (target 2.5 s or less), CLS measures unexpected layout movement (0.1 or less), and INP measures responsiveness to interactions (200 ms or less). To improve LCP, render critical content on the server, prioritize the hero image and reduce JavaScript. For CLS, reserve space with image dimensions and skeletons. For INP, avoid long tasks, defer non-urgent updates and keep renders small. Measure with field data first.
Full answer
Core Web Vitals are Google's user-experience metrics, measured on real visits (field data) and in lab tools such as Lighthouse.
Largest Contentful Paint (LCP): time until the biggest element in the viewport (often a hero image or heading) is rendered. Good is 2.5 seconds or less. In React apps the usual problems are an empty HTML shell, large JavaScript bundles delaying rendering, data waterfalls and unoptimized images. Fixes: server rendering or static generation so the HTML contains the content; code splitting and smaller bundles; start critical requests early; compress and size images, serve modern formats, set fetchPriority="high" on the LCP image and never lazy-load it; preload fonts.
Cumulative Layout Shift (CLS): how much visible content moves unexpectedly. Good is 0.1 or less. Causes: images without dimensions, content inserted above existing content (banners, late-loaded ads), web fonts swapping, and fallbacks (skeletons or spinners) with different sizes than the content. Fixes: set width and height or aspect-ratio, reserve space for dynamic content, use skeletons that match the final size, and avoid inserting items above the fold after load.
Interaction to Next Paint (INP): how long the page takes to respond visually after interactions throughout the visit. Good is 200 ms or less. In React this is about main-thread work: expensive renders, long handlers, hydration of large pages. Fixes: keep state local, memoize or use the Compiler where profiling shows waste, startTransition for heavy updates, split long tasks, virtualize long lists, lazy-load rarely used code, and use Web Workers for heavy computation. (See the INP debugging item.)
Process: collect real user data with the web-vitals library or your analytics, find the worst pages, reproduce with Lighthouse and the Performance panel under throttling, fix, and track by release.
Thresholds can change over time, so check the current definitions on web.dev.
The example shows an image and a placeholder that avoid shifts and prioritize the LCP element.
jsx
import { renderToStaticMarkup } from 'react-dom/server';
function Hero({ src }) {
// The LCP image: explicit size, high priority, never lazy.
return <img src={src} alt="Students in a class" width="1200" height="600" fetchPriority="high" />;
}
function Thumbnail({ src, title }) {
// Below the fold: lazy, with reserved space.
return <img src={src} alt={title} width="300" height="200" loading="lazy" decoding="async" />;
}
function CommentsPlaceholder() {
// A skeleton with the same height as the final content prevents layout shift.
return <div style={{ minHeight: 240 }} aria-busy="true" />;
}
console.log(
renderToStaticMarkup(
<main>
<Hero src="/hero.webp" />
<Thumbnail src="/course.webp" title="Course cover" />
<CommentsPlaceholder />
</main>
)
);
This ran as a script and prints the markup. It shows the attributes but not the metrics. React also emitted a preload link for the high-priority image on its own. Real measurement needs a browser and real users. Output of the run:
<link rel="preload" as="image" href="/hero.webp" fetchPriority="high"/><main><img src="/hero.webp" alt="Students in a class" width="1200" height="600" fetchPriority="high"/><img src="/course.webp" alt="Course cover" width="300" height="200" loading="lazy" decoding="async"/><div style="min-height:240px" aria-busy="true"></div></main>
Key points
LCP is loading speed, CLS is visual stability, and INP is responsiveness.
LCP: put content in the first HTML, prioritize the hero image, and reduce bundle size.
CLS: reserve space with dimensions and same-size skeletons.
INP: reduce main-thread work with transitions, local state, splitting and virtualization.
Measure with real-user data first, then verify fixes with lab tools.
Common mistakes
Lazy-loading the hero image that is the LCP element.
Leaving out image width and height or an aspect ratio.
Showing a skeleton that is smaller than the content.
Optimizing from lab scores without field data.
Shipping a large bundle for a mostly static page.
Follow-ups
How do you collect Core Web Vitals from real users?
Why can a spinner cause layout shift?
How do server rendering and hydration affect INP?
Tips
Give a number for each metric, and say numbers are checked against current guidance.
Offer one React-specific fix for each metric.
Say you measure with field data before optimizing.
127.react-0127Mediummid
What does memoization cost in React, and when does it make an app slower or more bug-prone instead of faster?
Memoization trades memory and comparison work for skipped renders. memo compares every prop on every parent render, useMemo and useCallback store values and compare dependencies, and all of them add code that can be stale or wrong. It only pays off when the skipped work is expensive and the inputs are stable. If props change every time (inline objects and functions) the comparison is wasted. Measure first, and prefer structural fixes (moving state down) or the React Compiler.
Full answer
Memoization avoids repeating work by remembering a previous result. In React the main tools are memo for components, useMemo for values and useCallback for functions.
Costs:
Time. memo runs a shallow comparison of all props on each parent render. For cheap components, comparing can cost about as much as rendering.
Memory. Cached values and old props are kept alive.
Complexity. Dependency arrays must be complete. A missing dependency gives stale values, and extra dependencies defeat the cache. Code becomes harder to read.
False confidence. A single unstable prop (an inline object, array or function, or a context value that changes) makes the whole memoization useless, yet the code still looks optimized.
When memoization helps: a component is expensive to render (large lists, charts) and its parent re-renders often with the same props; a value passed to a memoized child or to a dependency array must keep its identity; a calculation is genuinely heavy (measure, for example above a millisecond or so).
When it does not: simple components, props that change on most renders, state that changes on every keystroke in a parent that owns many children (better fix: move that state down), or premature use "just in case".
Alternatives and guidelines. Colocate state, pass children as props so elements keep identity, split components, virtualize long lists, and use useDeferredValue or transitions for heavy updates. The React Compiler memoizes automatically at build time using the rules of React, so manual memoization becomes the exception for cases such as effect dependency control. Measure with the Profiler before and after, and keep a memoization only if it shows an improvement.
The example shows memoized children that still re-render because of an unstable prop, and another that is skipped.
The check pressed the button once. The first row re-renders despite memo, because its style object is new every time. The other two are skipped. Output of the run:
List rendered, count 0
Row rendered: inline style object
Row rendered: constant style
Row rendered: useMemo style
List rendered, count 1
Row rendered: inline style object
Key points
Memoization costs comparison time, memory and added complexity.
One unstable prop (inline object or function) makes memo useless.
It helps for expensive renders or calculations with stable inputs. Measure first.
Moving state down and passing children often beat memoization.
The React Compiler reduces the need for manual memo, useMemo and useCallback.
Common mistakes
Wrapping components in memo while passing inline objects or functions.
Adding useMemo to cheap calculations.
Omitting dependencies and getting stale values.
Memoizing before profiling.
Ignoring that moving state down removes the need for memoization.
Follow-ups
How would you measure whether a memoization is worth keeping?
How does the React Compiler decide what to memoize?
Why can a context value defeat memo?
Tips
Frame memoization as a trade: cost versus skipped work.
Mention the one-unstable-prop problem.
Offer moving state down and the Compiler as alternatives.
128.react-0128Hardsenior
How do hooks work under the hood, and why do the rules of hooks require the same call order on every render?
React stores a component's hook state in an ordered list attached to its fiber. Each call to useState or useEffect reads the next slot in that list, because hooks have no names or keys, only their position. If the order or the number of calls changes between renders, a call reads the wrong slot, so React throws or returns another hook's state. That is why hooks must not be called in conditions, loops or after early returns.
Full answer
A hook such as useState(0) does not know which component called it. React tells it: during rendering, React sets a "current component" and a dispatcher. Inside it, each hook call looks at the component's list of hook records, one per call, and uses the next one.
In React's implementation, the fiber for a component has a memoizedState field that points to the first hook object. Each hook object holds its state (for useState, the value and an update queue) and a next pointer to the following hook, forming a linked list. On the first render (mount), each call creates a new node and appends it. On later renders (update), the calls walk the list from the start, one node per call, and reuse the stored state. The "cursor" is just position in the call order.
Consequences:
Calling hooks in the same order on every render keeps each call attached to the same node. That is the rule of hooks, and the lint rule enforces it.
A conditional hook shifts every following call by one. A later useState('b') then receives the node that belonged to another call, and React reports "Rendered fewer hooks than expected" or "Rendered more hooks than during the previous render".
Hooks cannot be called outside a render because there is no current fiber and dispatcher. That explains the invalid hook call error, which also happens with two copies of React (the hook uses the other copy's dispatcher).
State belongs to the component instance at a position in the tree, not to the hook name. Renaming variables does not matter, reordering calls does.
Effects have nodes too (with dependency arrays), and React compares dependencies per node.
Design benefits: composition. Custom hooks are only functions that call other hooks, so their state is simply appended to the same list. Two uses of one custom hook in a component create independent slots.
The example builds a tiny version with an array and a cursor, shows the shift caused by a conditional hook, then confirms with real React.
jsx
import { useState } from 'react';
import { createRoot } from 'react-dom/client';
// Part 1: a miniature model of hooks. State lives in a list, and a cursor follows the call order.
let slots = [];
let cursor = 0;
function useMiniState(initial) {
const index = cursor++;
if (!(index in slots)) slots[index] = initial;
return [slots[index], (value) => (slots[index] = value)];
}
function render(component) {
cursor = 0;
return component();
}
let showExtra = true;
function MiniComponent() {
// eslint-disable-next-line react-hooks/rules-of-hooks
if (showExtra) useMiniState('extra hook');
const [name] = useMiniState('Asha');
return name;
}
console.log('mini render 1 (extra hook called): ' + render(MiniComponent));
showExtra = false;
console.log('mini render 2 (extra hook skipped): ' + render(MiniComponent));
// Part 2: the same mistake in real React.
let callExtra = true;
function RealComponent() {
if (callExtra) {
// eslint-disable-next-line react-hooks/rules-of-hooks
useState('extra');
}
const [name] = useState('Asha');
return <p>{name}</p>;
}
const root = createRoot(document.getElementById('root'), {
onUncaughtError: (error) => console.log('real React: ' + error.message.split('\n')[0]),
});
root.render(<RealComponent />);
await new Promise((resolve) => setTimeout(resolve, 30));
callExtra = false;
root.render(<RealComponent />);
await new Promise((resolve) => setTimeout(resolve, 30));
Part 1 uses an array with a cursor instead of React's linked list, to show the principle. In part 2 the real React in development reports the changed hook count. The lint rule is disabled on purpose in this file to show the mistake. Output of the run:
mini render 1 (extra hook called): Asha
mini render 2 (extra hook skipped): extra hook
real React: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
Key points
Hook state is an ordered list on the component's fiber. The call order is the only identifier.
Mount creates nodes in order. Updates walk the same list from the start.
A conditional hook shifts later calls onto the wrong nodes, which is why call order must be stable.
Hooks need a current render and a single copy of React, or they throw an invalid hook call error.
Custom hooks work because they just append more nodes to the same list.
Common mistakes
Calling hooks inside conditions, loops or after an early return.
Reordering hook calls during a refactor without noticing.
Loading two copies of React and getting an invalid hook call error.
Calling hooks from regular functions or event handlers.
Assuming state is attached to the variable name.
Follow-ups
Why do custom hooks not need a special mechanism?
How does React know which dependencies array belongs to which effect?
What would a hooks system with named keys look like, and what would it cost?
Tips
Say "an ordered list per component" and "position is the identity".
Explain the conditional hook failure with the shifted slot.
Mention duplicate React copies as another cause of invalid hook calls.
129.react-0129Mediummid
What is the testing philosophy behind React Testing Library, in what order should you choose queries, and what should (and should not) you mock?
Test the component the way a user experiences it, not its internals. Choose queries in this order: getByRole (with name), getByLabelText, getByPlaceholderText, getByText, getByDisplayValue, getByAltText, getByTitle, and getByTestId only as a last resort. Mock only what you do not own or cannot run in a test: the network, timers, browser APIs and callback props. Do not mock your own child components or hooks, and do not assert on state or implementation details.
Full answer
The guiding principle of Testing Library is: "the more your tests resemble the way your software is used, the more confidence they can give you". A user finds a button by what it says and what role it has, not by a CSS class or a component name. Tests written this way survive refactors and also act as a basic accessibility check.
Query priority, from the documentation:
Accessible to everyone: getByRole (with the name option), getByLabelText, getByPlaceholderText, getByText, getByDisplayValue.
Semantic: getByAltText, getByTitle.
Last resort: getByTestId, because users cannot see test ids.
Variants: getBy throws if not found (use it when the element must exist), queryBy returns null (use it to assert absence), and findBy waits for an element to appear (use it after async work). The All versions return arrays. within(element) scopes a query. screen.logTestingPlaygroundURL() and getByRole error messages suggest better queries.
Interactions use @testing-library/user-event, which simulates real sequences (focus, key down, input, key up) and is more realistic than fireEvent.
What to mock:
The network (with Mock Service Worker, or a stubbed fetch in small tests), because tests must not depend on a server.
Time (fake timers) for debounce, polling and animations.
Browser APIs that jsdom lacks (matchMedia, IntersectionObserver).
Callback props, with vi.fn() or jest.fn(), to assert how the component reports events.
What not to mock: your own child components (a test of a page should render its real children), your own custom hooks, and React itself. Mocking internals makes tests pass while the real integration is broken. Do not test state values, instance methods or the number of renders.
Prefer a few integration tests of whole features over many shallow ones, and keep end-to-end tests for critical flows.
The example runs a test file that uses accessible queries and a callback mock.
jsx
import { useState } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom/vitest';
function Newsletter({ onSubscribe }) {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
function handleSubmit(event) {
event.preventDefault();
if (!email.includes('@')) {
setError('Enter a valid email');
return;
}
setError('');
onSubscribe(email);
}
return (
<form onSubmit={handleSubmit}>
<h2>Newsletter</h2>
<label>
Email address
<input value={email} onChange={(e) => setEmail(e.target.value)} />
</label>
{error && <p role="alert">{error}</p>}
<ul aria-label="Topics">
<li>React</li>
<li>TypeScript</li>
</ul>
<button type="submit">Subscribe</button>
</form>
);
}
afterEach(cleanup);
describe('Newsletter', () => {
it('finds elements the way a user would', () => {
render(<Newsletter onSubscribe={vi.fn()} />);
expect(screen.getByRole('heading', { name: 'Newsletter' })).toBeInTheDocument();
expect(screen.getByLabelText('Email address')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Subscribe' })).toBeEnabled();
expect(within(screen.getByRole('list', { name: 'Topics' })).getAllByRole('listitem')).toHaveLength(2);
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
it('shows an error for an invalid email and does not call the callback', async () => {
const user = userEvent.setup();
const onSubscribe = vi.fn();
render(<Newsletter onSubscribe={onSubscribe} />);
await user.type(screen.getByLabelText('Email address'), 'asha');
await user.click(screen.getByRole('button', { name: 'Subscribe' }));
expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid email');
expect(onSubscribe).not.toHaveBeenCalled();
});
it('reports a valid email through the callback prop', async () => {
const user = userEvent.setup();
const onSubscribe = vi.fn();
render(<Newsletter onSubscribe={onSubscribe} />);
await user.type(screen.getByLabelText('Email address'), 'asha@example.com');
await user.click(screen.getByRole('button', { name: 'Subscribe' }));
expect(onSubscribe).toHaveBeenCalledWith('asha@example.com');
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
});
Only the callback prop is mocked, and the real component runs. The file ran under Vitest with jsdom, and these tests passed on two consecutive runs:
Newsletter > finds elements the way a user would
Newsletter > shows an error for an invalid email and does not call the callback
Newsletter > reports a valid email through the callback prop
Key points
Test behaviour from the user's point of view, not implementation details.
Query order: role, label, placeholder, text, display value, alt text, title, and test id last.
Use getBy for present, queryBy for absent and findBy for async elements. Prefer user-event.
Mock the network, time, missing browser APIs and callback props.
Do not mock your own components or hooks, and do not assert on state or render counts.
Common mistakes
Using getByTestId when a role or label query exists.
Mocking child components or custom hooks in a test of a parent.
Asserting on state, props or the number of renders.
Using getBy to check that something is absent.
Using fireEvent for typing instead of user-event.
Follow-ups
Why does getByRole make a test double as an accessibility check?
How would you test a component that depends on a context provider?
When is a snapshot test appropriate?
Tips
Quote the guiding principle in your own words.
Know the query order and the three query variants.
Say you mock the boundary, not your own code.
130.react-0130Mediummid
How do you use React DevTools and the Profiler to debug state and find slow renders?
The Components tab shows the component tree with props, state, hooks and context that you can inspect and edit live, and highlights what renders. The Profiler tab records interactions and shows a flame chart and a ranked chart of render times, plus why each component rendered. Enable "Highlight updates when components render" and "Record why each component rendered". Profile production-like builds, because development is slower. The Profiler component and useDebugValue add code-level hooks.
Full answer
React DevTools is a browser extension (and standalone app) that understands React's internal tree.
Components tab. It lists components as they are nested, not the DOM. Selecting one shows its props, state, hooks (in order, with custom hook names), context values and the source location. You can edit props, state and hook values live to test cases, jump to the DOM node, and find components by name. The "Highlight updates when components render" setting flashes borders around components when they re-render, which quickly reveals unnecessary updates. Settings also allow filtering components (hide host elements or library internals) and showing Strict Mode double render logs.
Profiler tab. Start recording, perform an interaction, stop. The flame chart shows each commit: how long each component took to render, with gray components not rendered in that commit. The ranked chart sorts components by render time. Turn on "Record why each component rendered while profiling" to see reasons such as "props changed (name)", "hooks changed", "parent rendered". Commits can be stepped through. Timings are only meaningful in a production-like build, because development builds are slower. React provides a profiling build for production measurements.
Code-level tools:
<Profiler id onRender> wraps a subtree and calls back with the phase (mount, update, nested-update), actual and base durations, and commit time. It works in development and profiling builds and is disabled in a normal production build.
useDebugValue(value) adds a label to a custom hook in DevTools.
displayName improves names of anonymous or wrapped components (memo, forwardRef).
The Performance panel of the browser shows the same renders in the context of long tasks and paint, which is where INP issues become visible.
Workflow: reproduce the slow interaction, profile, find the components that render too often or take longest, read why, apply the fix (move state, memo, split, virtualize), profile again and compare.
The example uses the Profiler component and useDebugValue.
The Profiler callback fired for the first render (mount) and for the click (update). The DevTools panels cannot be run in this environment, so the tab descriptions come from the documentation and not from a run here. Output of the run:
Profiler counter-area: phase=mount, duration is a number=true
Profiler counter-area: phase=update, duration is a number=true
Key points
The Components tab inspects and edits props, state, hooks and context, and can highlight re-renders.
The Profiler records commits with flame and ranked charts, and can show why components rendered.
Profile production-like builds for meaningful timings.
The Profiler component, useDebugValue and displayName provide code-level hooks.
Workflow: reproduce, profile, read the reason, fix, profile again.
Common mistakes
Measuring performance in the development build.
Optimizing without checking why a component rendered.
Leaving Profiler wrappers in production code and expecting data (they are disabled in normal production builds).
Ignoring unnamed components, which make the tree hard to read.
Reading the flame chart without using the ranked view for the worst offenders.
Follow-ups
What does "why did this render" tell you, and what are the common reasons?
How do you profile a production build?
How does the Performance panel complement the React Profiler?
Tips
Mention both tabs and one setting for each.
Say you profile production-like builds.
Name the Profiler component as the programmatic option.
131.react-0131Mediummid
What is Storybook, why do React teams use it, and how do you write a story?
Storybook is a tool for building and documenting UI components in isolation. Each component has stories, which are named examples of it in specific states, written as small objects in Component Story Format (CSF). Teams use it to develop without running the whole app, to document a design system, to review visual states, and to run interaction, accessibility and visual regression tests on each story.
Full answer
Building a component inside the full application makes it hard to reach edge states (loading, error, long text, empty list). Storybook gives each component its own workshop with a gallery of states.
Writing stories. A story file sits next to the component, such as Button.stories.jsx. It has a default export called meta, which describes the component (title, component, shared args, parameters), and named exports, one per story. In CSF3, a story is an object with args (the props), and optionally render, play and decorators:
Isolated development. Build and tweak a component with hot reload without logging in or navigating to the right screen.
Documentation and a shared language. Autodocs generate prop tables from types and stories, so designers, developers and QA see the same catalogue (a living design system).
Testing. play functions simulate user interactions (using Testing Library utilities) and assert the result in the browser. The a11y addon runs axe on each story. Visual regression tools (Chromatic, Percy or similar) screenshot each story and detect unintended changes. Stories can be reused in Vitest tests by composing them.
Review. Pull requests can publish a Storybook build for review.
Practical points: use decorators to wrap stories in providers (theme, router, query client), mock network calls with MSW, keep stories small and focused on states, and avoid stories for every trivial component. Storybook adds configuration and maintenance, so it pays off most for shared component libraries and design systems.
The example is a button with stories, rendered here by a small script that merges meta args and story args as Storybook does.
jsx
function Button({ variant = 'secondary', disabled = false, children }) {
return (
<button className={'btn btn-' + variant} disabled={disabled}>
{children}
</button>
);
}
// Button.stories.jsx: a default export with metadata, and a named export per story (CSF3).
export default {
title: 'Components/Button',
component: Button,
args: { children: 'Save' },
};
export const Primary = { args: { variant: 'primary' } };
export const Secondary = {};
export const Disabled = { args: { disabled: true } };
Storybook itself was not run. A small script rendered each story the way Storybook does, by merging meta args with story args, to check the examples. Output of the run:
Disabled -> <button class="btn btn-secondary" disabled="">Save</button>
Primary -> <button class="btn btn-primary">Save</button>
Secondary -> <button class="btn btn-secondary">Save</button>
Key points
Storybook develops and documents components in isolation, as a catalogue of states.
Stories are CSF objects: a default meta export and named exports with args.
Autodocs, interaction tests, accessibility checks and visual regression use the same stories.
Decorators provide context (theme, router, data), and MSW mocks the network.
It pays off most for shared libraries and design systems.
Common mistakes
Writing stories that only show the default state.
Leaving out decorators and getting components that crash without their providers.
Letting stories drift from real usage because nobody runs them in CI.
Creating a story for every tiny component and overloading maintenance.
Calling Storybook a test tool without adding play functions or visual tests.
Follow-ups
What is a play function and what does it let you test?
How would you handle components that need a router or a data provider?
How does visual regression testing with stories work?
Tips
Describe stories as named states of a component.
Mention the three uses: develop, document and test.
Say it pays off most for shared component libraries.
132.react-0132Mediummid
What is a monorepo, why do React teams use one, and how do workspaces and build caching work?
A monorepo keeps several apps and packages (a web app, a mobile app, a design system, shared utilities) in one repository. Package manager workspaces (pnpm, npm or yarn) link local packages so changes are used immediately, and tools such as Turborepo or Nx run tasks in dependency order and cache results. Benefits are shared code, atomic changes and consistent tooling. Costs are tooling complexity, slower CI without caching, and the need for clear boundaries and ownership.
Full answer
In a polyrepo setup each app and library has its own repository and version. Sharing a component library means publishing a package, bumping versions and updating every consumer. In a monorepo they live together, which changes the workflow.
Structure. A common layout is apps/web, apps/admin, packages/ui (design system), packages/config (ESLint, TypeScript and Prettier presets) and packages/utils. The root declares workspaces, for example in pnpm-workspace.yaml. Packages depend on each other using the workspace protocol ("@acme/ui": "workspace:*"), so the package manager links the local folder instead of downloading it.
Task running and caching. Running build in the right order matters: ui before web. Turborepo and Nx read the dependency graph, run tasks in parallel where possible, and cache outputs keyed by the inputs (source files, dependencies, environment). If nothing changed, the result is restored in seconds. Remote caching shares results between CI and developers. Affected-only commands run tests for packages touched by a change.
Benefits: share and refactor code across apps in one pull request, one set of tool versions, easier code reuse and discoverability, and a single source of truth for dependency versions (pnpm catalogs help).
Costs and pitfalls: tooling and onboarding complexity, CI that runs everything unless it uses caching and filtering, accidental coupling between packages (enforce boundaries with lint rules), permissions and ownership (CODEOWNERS), and phantom dependencies (pnpm's strict node_modules helps catch packages that are imported but not declared). Internal packages may be consumed as source (transpiled by the app's bundler) for speed, or built to dist for publishing, which is a design choice.
Not every project needs one. A single app with a single team rarely benefits.
The example is a pnpm workspace file with a shared version catalog. It is configuration and was not executed.
yaml
# pnpm-workspace.yaml at the repository root
packages:
- "apps/*"
- "packages/*"
# Shared versions: packages write "react": "catalog:" in their package.json
catalog:
react: ^19.2.0
react-dom: ^19.2.0
typescript: ^5.9.0
This is a configuration file and was not executed. Its YAML syntax was parsed with a YAML library to confirm it is valid. The catalog feature needs a recent pnpm version, and the versions shown are examples to adapt.
Key points
A monorepo holds several apps and packages in one repository with shared tooling.
Workspaces link local packages. The workspace protocol resolves them from the repo.
Turborepo and Nx run tasks in dependency order and cache results, including remote caches.
Benefits: shared code, atomic changes, consistent versions. Costs: tooling complexity and CI time without caching.
Enforce package boundaries and declare every dependency.
Common mistakes
Creating a monorepo for one small app and paying the tooling cost.
Running every package's tests on every change because caching is not set up.
Importing from another package's internal files instead of its public entry.
Importing packages that are not declared in package.json.
Having no owners or boundaries, so any team changes any package.
Follow-ups
How do you decide whether internal packages are built or consumed as source?
How would you run only the tests affected by a pull request?
How do you version and publish packages from a monorepo?
Tips
Describe the layout and the workspace protocol.
Explain task caching, since it is what makes monorepos fast.
Say a single small app does not need one.
133.react-0133Mediummid
How do environment variables work in a Vite React app, and why must you never put secrets in them?
Vite exposes only variables whose names start with VITE_ to client code through import.meta.env, and replaces them with literal values at build time. Anything in the bundle is public, so API keys that must stay secret cannot be stored there. Use VITE_ variables only for non-secret configuration such as a public API URL, and keep secrets on a server. Changing a value requires a rebuild, unlike a server that reads its environment at runtime.
Full answer
A React app built with Vite runs in the user's browser. There is no "private" environment there. So the design of environment variables in Vite is about what gets copied into the bundle.
How it works. Vite reads .env files (.env, .env.local, .env.production and mode-specific files) and the process environment. Only variables prefixed with VITE_ are exposed to client code as import.meta.env.VITE_API_URL. Other variables, such as DB_PASSWORD, stay out of the bundle. Built-in values include import.meta.env.MODE, DEV, PROD, BASE_URL. During the build, Vite statically replaces these expressions with their values, which is why they are constants in the output and why changing them requires a new build.
Security rule. Everything in the client bundle can be read by anyone (View Source, network tab). A VITE_STRIPE_SECRET_KEY would be public the moment you deploy. Public keys (a Stripe publishable key, a Maps key restricted by domain, an analytics id) are fine. Secrets (database credentials, private API keys, signing keys) belong on a server or serverless function that your app calls. The VITE_ prefix is a guard against accidental exposure, but a developer can still name a secret with the prefix, so review variables in code review. Do not commit .env.local or files with secrets; commit an .env.example.
Deployment. Because values are baked in, build once per environment, or avoid per-environment builds by loading runtime configuration from a small /config.json or an injected script that the server generates. TypeScript users declare variable types in vite-env.d.ts.
Other tools differ: Next.js uses the NEXT_PUBLIC_ prefix for client variables and keeps others on the server, and Create React App used REACT_APP_.
The example runs a real Vite build with a secret and a public variable in a .env file, and searches the output.
jsx
import { build } from 'vite';
import { mkdtemp, readdir, readFile, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
const root = await mkdtemp(path.join(tmpdir(), 'vite-env-'));
await writeFile(path.join(root, '.env'), 'VITE_API_URL=https://api.example.com\nDB_PASSWORD=never-ship-this\n');
await writeFile(path.join(root, 'index.html'), '<div id="root"></div><script type="module" src="/main.js"></script>');
await writeFile(
path.join(root, 'main.js'),
'console.log(import.meta.env.VITE_API_URL, import.meta.env.DB_PASSWORD, import.meta.env.MODE);\n'
);
await build({ root, configFile: false, logLevel: 'silent', build: { outDir: path.join(root, 'out') } });
const assets = path.join(root, 'out', 'assets');
const files = await readdir(assets);
const bundle = await readFile(path.join(assets, files.find((f) => f.endsWith('.js'))), 'utf8');
console.log('public value is inlined: ' + bundle.includes('https://api.example.com'));
console.log('secret value is in the bundle: ' + bundle.includes('never-ship-this'));
console.log('MODE replaced with production: ' + bundle.includes('production'));
console.log('import.meta.env is left in the code: ' + bundle.includes('import.meta.env'));
This ran a real Vite build of a tiny project in a temporary folder. The VITE_ variable was copied into the output, while the other variable was not. The script only verifies the inlining, and does not use React. Output of the run:
public value is inlined: true
secret value is in the bundle: false
MODE replaced with production: true
import.meta.env is left in the code: false
Key points
Only variables prefixed with VITE_ reach client code through import.meta.env.
Values are inlined at build time, so changes need a rebuild.
Anything in the bundle is public. Never store secrets in client variables.
Keep secrets on a server and expose only public configuration.
Commit .env.example, not secret files. Next.js uses NEXT_PUBLIC_ in the same role.
Common mistakes
Putting API secrets in VITE_ variables.
Expecting to change a variable on the server without rebuilding the client.
Committing .env files with real secrets.
Assuming the VITE_ prefix makes a value private.
Using one build for several environments without runtime configuration.
Follow-ups
How would you provide different API URLs per environment without rebuilding?
How do you type import.meta.env in TypeScript?
How do server frameworks keep non-public variables off the client?
Tips
State the rule: the bundle is public.
Explain the prefix as a guard, not as security.
Mention runtime configuration as the way to avoid per-environment builds.
134.react-0134Mediummid
How do you deploy a React single-page app, and what do the SPA fallback and cache headers have to do with it?
A client-rendered React app builds to static files that any static host or CDN can serve. Two server rules are essential. The server must return index.html for any route that is not a real file, otherwise deep links and page refreshes return 404. Hashed asset files should be cached for a long time as immutable, while index.html should not be cached, so users get new versions. Server-rendered apps need a Node or edge runtime instead.
Full answer
The build output of a Vite or similar SPA is a folder with index.html and hashed JavaScript, CSS and image files in an assets folder. Deployment means putting that folder behind a web server or CDN: Netlify, Vercel, Cloudflare Pages, GitHub Pages, S3 with CloudFront, or an Nginx server.
Rule 1: the SPA fallback. With client-side routing, a URL like /courses/react-basics exists only inside the app. If a user refreshes or opens that link, the server looks for a file named that path and finds nothing. The fix is a rewrite: for any path that is not a real file, return index.html with status 200, and let the router render the page. Hosts have a setting for it (Netlify _redirects with /* /index.html 200, Vercel rewrites, an Nginx try_files $uri /index.html). Requests for missing assets should still return 404 so that errors are visible. Your app should render its own not-found page for unknown routes.
Rule 2: cache headers. Build tools add a content hash to file names (app.3f9a1c.js). A changed file gets a new name, so old names can be cached for a year with Cache-Control: public, max-age=31536000, immutable. index.html refers to the current hashed files, so it must always be revalidated: Cache-Control: no-cache. Otherwise users get a stale HTML that points to files that may no longer exist after a deploy, a common source of "ChunkLoadError" bugs. Keep old assets available for a while after deploy, or handle chunk load errors by prompting a reload.
Other points:
Compression (gzip or Brotli) and HTTP/2 or HTTP/3, usually provided by the CDN.
Environment configuration is baked in at build time (see the Vite environment variable item), so build per environment or use runtime config.
Security headers (Content-Security-Policy, HSTS) and HTTPS.
Preview deployments for each pull request, and rollbacks by redeploying a previous build.
A base path if the app is served from a subfolder (base option in Vite and the router's basename).
Server-rendered apps (Next.js and similar) run on a Node server, serverless functions or edge runtime, and static parts go to the CDN.
The example is a small Node server with the fallback and cache rules, tested with real requests.
jsx
import http from 'node:http';
const files = {
'/index.html': '<div id="root"></div><script src="/assets/app.3f9a1c.js"></script>',
'/assets/app.3f9a1c.js': 'console.log("app")',
};
const server = http.createServer((request, response) => {
const pathname = new URL(request.url, 'http://localhost').pathname;
if (pathname.startsWith('/assets/')) {
if (!files[pathname]) {
response.writeHead(404);
return response.end('not found');
}
response.writeHead(200, {
'content-type': 'text/javascript',
'cache-control': 'public, max-age=31536000, immutable',
});
return response.end(files[pathname]);
}
// SPA fallback: any other path gets index.html, and the router decides what to show.
response.writeHead(200, { 'content-type': 'text/html', 'cache-control': 'no-cache' });
response.end(files['/index.html']);
});
await new Promise((resolve) => server.listen(0, resolve));
const base = 'http://localhost:' + server.address().port;
for (const route of ['/', '/courses/react-basics', '/assets/app.3f9a1c.js', '/assets/missing.js']) {
const res = await fetch(base + route);
console.log(route + ' -> ' + res.status + ', cache-control: ' + (res.headers.get('cache-control') ?? 'none'));
}
server.close();
This ran a real HTTP server on a random local port and requested four paths with fetch. The deep link returns index.html with status 200, the hashed asset gets the long cache header, and a missing asset returns 404. Output of the run:
/ -> 200, cache-control: no-cache
/courses/react-basics -> 200, cache-control: no-cache
/assets/app.3f9a1c.js -> 200, cache-control: public, max-age=31536000, immutable
/assets/missing.js -> 404, cache-control: none
Key points
A client-rendered build is static files that any static host or CDN can serve.
Return index.html for unknown non-asset routes, so deep links and refreshes work.
Cache hashed assets as immutable for a long time and revalidate index.html always.
Handle missing assets with 404 and show an in-app not-found page for unknown routes.
Plan for environment variables, a base path, security headers, previews and rollbacks.
Common mistakes
Forgetting the index.html fallback and getting 404 on refresh.
Caching index.html for a long time, so users stay on an old version.
Serving a missing asset as index.html with status 200, which hides errors.
Deleting old assets immediately after a deploy.
Setting the wrong base path for an app served from a subfolder.
Follow-ups
How would you handle a ChunkLoadError after a new deployment?
What changes when you deploy a server-rendered Next.js app?
How do preview deployments and rollbacks work on your platform?
Tips
Lead with the two rules: fallback and caching.
Explain why hashed names allow immutable caching.
Mention the stale index.html problem and chunk load errors.
135.react-0135Hardsenior
How do state libraries such as Redux, Zustand and Context differ in how they notify components, and how would you build a minimal selector-based store?
Context re-renders every consumer when its value changes, with no way to select a part. Redux and Zustand keep state in a store outside React and let components subscribe with a selector, so a component re-renders only when the selected slice changes. Both are built on useSyncExternalStore. Atomic libraries such as Jotai go further, with each atom having its own subscribers. A minimal store is a few lines: state, a listener set, setState and a hook that passes a selector.
Full answer
All state tools answer two questions: where does state live, and how do components find out that it changed.
Context. The value is held by a provider component. When the value changes, React re-renders all components that call useContext on it, because context has no selector. It is ideal for rarely changing values (theme, user, locale) and inconvenient for frequently changing state, unless you split contexts or memoize.
External store with selectors (Redux, Zustand). State lives outside React in a plain JavaScript object. Components subscribe through a hook such as useSelector(state => state.cart.count) or useStore(s => s.count). When the store changes, every subscriber runs its selector and compares the result with the previous one using Object.is (or a custom equality). Only components whose selected value changed re-render. Redux adds a strict pattern (actions, reducers, middleware, devtools). Zustand is a small store with functions in the state object and no provider requirement.
Atomic state (Jotai, and the idea behind Recoil). State is split into small atoms, and components subscribe to specific atoms. Derived atoms recompute when their inputs change. Updates are precise by construction.
Proxy-based and mutable styles (Valtio, MobX) track which properties each component reads and re-render only for those.
The React integration point is useSyncExternalStore(subscribe, getSnapshot). It subscribes, reads the current value during render, and keeps all components consistent under concurrent rendering (no tearing). The rules: getSnapshot must return a stable value when the state did not change, so selectors should return primitives or existing references, and not build new objects on each call.
Choosing: Context for slow, app-wide configuration. A store for frequently changing client state shared across distant components. A data library (TanStack Query, RTK Query) for server state. Local state for the rest.
The example builds a small store with selectors and shows that only the component reading the changed slice re-renders.
jsx
import { useSyncExternalStore } from 'react';
function createStore(initial) {
let state = initial;
const listeners = new Set();
return {
setState(update) {
state = { ...state, ...update(state) };
listeners.forEach((listener) => listener());
},
useStore(selector) {
return useSyncExternalStore(
(listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
() => selector(state)
);
},
};
}
const { setState, useStore } = createStore({ a: 0, b: 0 });
function CounterA() {
const a = useStore((state) => state.a);
console.log('CounterA rendered with ' + a);
return <button onClick={() => setState((s) => ({ a: s.a + 1 }))}>Add A ({a})</button>;
}
function CounterB() {
const b = useStore((state) => state.b);
console.log('CounterB rendered with ' + b);
return <button onClick={() => setState((s) => ({ b: s.b + 1 }))}>Add B ({b})</button>;
}
export default function App() {
return (
<div>
<CounterA />
<CounterB />
</div>
);
}
The check pressed Add A and then Add B. Each press re-rendered only the component whose selected value changed. Output of the run:
CounterA rendered with 0
CounterB rendered with 0
CounterA rendered with 1
CounterB rendered with 1
Key points
Context re-renders all consumers on any value change and has no selectors.
Redux and Zustand subscribe with selectors, so only components with a changed slice re-render.
Atomic and proxy-based libraries track dependencies even more precisely.
useSyncExternalStore connects external stores to React safely, with stable snapshots.
Choose context for slow config, a store for shared client state, and a data library for server state.
Common mistakes
Putting fast-changing state in a single context and re-rendering every consumer.
Writing a selector that returns a new object or array every time.
Selecting the whole state in a store hook.
Mutating the state object inside the store.
Choosing a global store for state that is local to one component.
Follow-ups
Why must the getSnapshot function return a cached value?
How do Jotai atoms differ from selectors on a single store?
How would you add middleware or devtools support to this store?
Tips
Compare the notification models, not only the APIs.
Mention useSyncExternalStore as the common foundation.
Warn about selectors that create new objects.
136.react-0136Hardsenior
What happens in the render phase and the commit phase in what order, and where do refs, layout effects and passive effects run?
The render phase runs your components to compute the new tree, and it may be paused, repeated or discarded, so it must be pure. The commit phase then applies changes to the DOM synchronously and cannot be interrupted. In commit, React removes old refs and runs cleanups for layout effects, mutates the DOM, attaches refs and runs layout effects (before the browser paints), and later runs passive effects (useEffect), usually after paint.
Full answer
React splits an update into two phases.
Render phase (also called reconciliation). React calls your function components (and class render methods), compares the result with the previous tree, and marks what must change. No DOM is touched. In concurrent mode this phase can be interrupted, restarted, or thrown away, which is why render must be free of side effects. Component bodies run here, including useMemo and useState initializers.
Commit phase. React applies the result to the DOM in one synchronous pass, which cannot be paused, so users never see a half-updated screen. It has sub-steps:
Before mutation: reads from the DOM (class getSnapshotBeforeUpdate).
Mutation: inserts, updates and removes DOM nodes. Cleanups of layout effects and detaching of old refs happen here.
Layout: refs are attached and useLayoutEffect callbacks (and class componentDidMount and componentDidUpdate) run. The DOM is updated, but the browser has not painted yet, so you can measure with getBoundingClientRect and update state synchronously to avoid flicker.
Passive effects: useEffect cleanups and callbacks run after the browser has had a chance to paint, so they do not delay visuals. When an update was caused by a discrete event such as a click, React may flush passive effects synchronously before the next render to keep state consistent.
Ordering inside a phase follows the tree: children complete before parents, so a child's layout effect and ref attach run before its parent's layout effect.
Implications. Do measuring and DOM synchronization in layout effects, data fetching and subscriptions in passive effects. Never perform side effects in the render phase. Refs are not set during render, so you can only read ref.current in effects and handlers. Strict Mode adds a render, and an extra mount, unmount, mount of effects in development.
The example logs every step for a mount and one update.
The log shows the mount first and then the update after the click. Note that the layout effect already sees the new DOM text. On the update, the old layout cleanup runs before the new layout effect, and the old passive cleanup runs after the layout effect, just before the new passive effect. Output of the run:
render phase: count=0
layout effect: DOM text is "Clicked 0"
passive effect: count=0
render phase: count=1
layout effect cleanup
layout effect: DOM text is "Clicked 1"
passive effect cleanup: count=0
passive effect: count=1
layout effect cleanup
passive effect cleanup: count=1
Key points
Render computes the new tree, is interruptible and must be pure. Commit applies it synchronously.
Commit order: mutate the DOM, attach refs and run layout effects, then run passive effects after paint.
Layout effects can measure the DOM before paint. Passive effects do not block painting.
Children complete before parents in the same phase.
Refs are not available during render. Read them in effects or handlers.
Common mistakes
Reading or writing the DOM during render.
Using useEffect for measurements and causing a visible flicker.
Expecting ref.current to be set during render.
Putting subscriptions in the render body.
Assuming effects run before the browser paints.
Follow-ups
Why does React keep the commit phase synchronous?
When can passive effects run before the paint?
How does Strict Mode change effect timing in development?
Tips
Describe the phases as "compute, then apply".
Name the commit sub-steps in order with where refs and layout effects fit.
Mention that render can be repeated, which is the reason for purity.
137.react-0137Hardsenior
How does React bail out of updates (same state value, same element, memo), and why can a component render one extra time even when state did not change?
If you set state to a value that is identical (Object.is) to the current one, React can skip the update. In the simplest case it skips scheduling entirely. In other cases React calls the component once more to check, then stops without rendering children or running effects. So an extra function call may happen, but no child render and no commit. Separate bailouts exist for unchanged elements (same identity) and for memo with equal props.
Full answer
React tries to avoid work at several levels.
State bailout. When setCount(value) is called with the same value as the current state (compared with Object.is), React may skip the update. There is an eager path: if the component has no pending updates, React calculates the next state immediately when you call the setter, sees it is equal, and does not schedule a render at all. When the component already has pending work or the eager check cannot be used, React schedules a render, calls your component function, finds that the state is unchanged, and bails out: it discards the result, does not render children, and does not run effects. That is the case when you may see one extra log from the component body, and it is not a bug.
Identity bailout for elements. If an element object is identical to the previous one (same type, same props object), React skips the subtree. This is what happens for children passed through from a parent that did not re-render.
memo. React compares props with Object.is per prop (shallow equality) and skips rendering the component if all are equal and its own state and context did not change.
Context and selectors bail out by comparing the new value with the old one. Unchanged useMemo and useCallback results keep identities that make the other bailouts work.
Practical consequences: do not rely on the number of component function calls to infer commits. Side effects in the body will show these extra calls (another reason for purity). Mutating state and setting the same reference is a bailout, so the UI does not update. For objects, always create a new one when something changed.
The example logs renders in a parent and child while setting the same value repeatedly.
jsx
import { memo, useState } from 'react';
const Child = memo(function Child() {
console.log(' Child rendered');
return <p>child</p>;
});
export default function Parent() {
const [count, setCount] = useState(0);
console.log('Parent body called, count=' + count);
return (
<div>
<button onClick={() => setCount(1)}>Set to 1</button>
<button onClick={() => setCount(count + 0)}>Set to the same value</button>
<Child />
</div>
);
}
The check pressed Set to 1 first, and then Set to the same value. The first press logged one Parent call and no Child render, because memo skipped the unchanged child. The second press, with the same value, logged one more Parent call with count=1 and no Child render. That extra call is the bailout check. Output of the run:
Parent body called, count=0
Child rendered
Parent body called, count=1
Parent body called, count=1
Key points
Setting state to an identical value (Object.is) lets React skip the update.
React may call the component one extra time before bailing out, without rendering children or running effects.
Identical elements and memo with equal props skip subtrees.
Do not infer commits from component function calls, and keep render pure.
Mutating state and setting the same reference is a bailout, so the UI will not change.
Common mistakes
Counting component function calls as proof of commits.
Mutating a state object and calling the setter with the same reference.
Putting side effects in the body and being surprised by extra calls.
Expecting a same-value update to run effects.
Assuming memo skips the component's own state updates.
Follow-ups
What is the eager state computation, and when does it not apply?
How does React decide that an element subtree can be skipped?
What does the React Compiler change about these checks?
Tips
List the bailout levels: state, element identity, memo, context.
Explain the extra call as a check, not a commit.
Tie it back to render purity.
138.react-0138Hardsenior
How does fine-grained reactivity (signals) differ from React's re-render model, and what are the trade-offs?
React re-runs component functions and diffs the output when state changes, so the unit of update is the component. Signal-based systems (Solid, Vue's refs, Angular signals, Preact signals) track which computations read each value and re-run only those when it changes, so the unit of update is the individual binding. Signals avoid re-render and memoization work, but React's model is simpler to reason about (UI is a function of state) and has a larger ecosystem. React Compiler narrows the gap with automatic memoization.
Full answer
Two ways of answering "what should update when this value changes?".
React: coarse updates by re-rendering. A state change schedules a render of that component and its children. React runs the functions and compares the new elements to the old ones (reconciliation), then updates the DOM where they differ. The programming model is simple: components are pure functions of props and state, and no dependency tracking is declared by you (except in hook dependency arrays). The cost is repeated work for unchanged parts, which memo, state colocation and the Compiler reduce.
Signals: fine-grained updates by tracking. A signal is a container for a value with a get and set. When a computation (a derived value or an effect that updates a piece of DOM) reads a signal, the system records that dependency. When the signal changes, it re-runs only the computations that depend on it, and updates just those DOM nodes. The component function in Solid runs once, and later updates are done by these tracked bindings. In Vue, ref and reactive do the same through proxies, and Angular signals provide it with change detection integration.
Trade-offs:
Performance: signals avoid diffing and unnecessary child execution, so they often scale better for frequently changing, fine-grained data. React's overhead is typically acceptable and is improving.
Mental model: React's re-render model means plain JavaScript semantics (values are snapshots). With signals you must remember that reading signal.value inside tracked scopes creates dependencies, and destructuring props or reading values outside tracking can lose reactivity.
Ecosystem and tooling: React has the largest library ecosystem, React Native and Server Components.
Control: React exposes render and commit semantics for concurrency, transitions and Suspense. Signal libraries are exploring similar features.
React Compiler memoizes components and values at build time, which brings some of the benefit of fine-grained updates without changing the model. Preact offers signals that can bind directly to the DOM within a React-like API.
The example is a short signal implementation that updates only the dependent effect.
jsx
let currentEffect = null;
function signal(initial) {
let value = initial;
const subscribers = new Set();
return {
get() {
if (currentEffect) subscribers.add(currentEffect);
return value;
},
set(next) {
if (Object.is(next, value)) return;
value = next;
subscribers.forEach((run) => run());
},
};
}
function effect(fn) {
const run = () => {
currentEffect = run;
fn();
currentEffect = null;
};
run();
}
const firstName = signal('Asha');
const lastName = signal('Rao');
const counter = signal(0);
effect(() => console.log('name binding ran: ' + firstName.get() + ' ' + lastName.get()));
effect(() => console.log('counter binding ran: ' + counter.get()));
console.log('--- change counter');
counter.set(1);
console.log('--- change firstName');
firstName.set('Meera');
console.log('--- set firstName to the same value');
firstName.set('Meera');
This is plain JavaScript with a tiny signal model and no React. Each effect re-ran only when a signal it read changed. In React, the equivalent state change would run the component function again. Output of the run:
name binding ran: Asha Rao
counter binding ran: 0
--- change counter
counter binding ran: 1
--- change firstName
name binding ran: Meera Rao
--- set firstName to the same value
Key points
React updates by re-rendering components and diffing. Signals track dependencies and update exact bindings.
Signals avoid repeated work and memoization, but need care to keep reads tracked.
React's model is simpler to reason about and has a larger ecosystem and concurrency features.
The React Compiler reduces unnecessary work without changing the model.
Choose by update patterns, team knowledge and ecosystem needs.
Common mistakes
Saying signals are always faster than React.
Destructuring reactive values and losing tracking in signal libraries.
Assuming React tracks dependencies automatically.
Ignoring the ecosystem and hiring side of the decision.
Comparing frameworks with micro-benchmarks only.
Follow-ups
How does the React Compiler narrow the gap with signals?
What happens to a signal-based component function after the first run?
How do Angular signals integrate with change detection?
Tips
Define the unit of update for each model.
Give one honest advantage for each side.
Mention the Compiler as React's answer.
139.react-0139Hardsenior
How do useDeferredValue, debouncing and throttling differ for responsive search inputs, and when do you combine them?
Debounce waits until the user stops for a fixed time before running work, which is useful to reduce network requests. Throttle runs work at most once per interval. useDeferredValue has no fixed delay: React renders the urgent update first, then renders with the deferred value in the background, and abandons it if a newer value arrives. It helps with slow rendering, not slow networks. Use debounce or throttle to limit requests and useDeferredValue to keep typing smooth during heavy renders.
Full answer
All three tools keep an interface responsive while input changes quickly, but they solve different problems.
Debounce. It restarts a timer on each event and runs the callback only after a quiet period (for example 300 ms). The cost is a guaranteed delay, even on fast devices. Best for network calls such as search suggestions, where the problem is the number of requests. Throttle runs the callback at most once per period (for example every 100 ms during scrolling), giving regular updates during continuous events. Both are timing-based and independent of rendering.
useDeferredValue(value). It returns the previous value during an urgent render and schedules a lower-priority render with the new value. While the background render runs, React keeps the input responsive. If the user types again, the unfinished background render is discarded, so intermediate values may never render. There is no fixed delay: on a fast device the deferred render completes almost immediately, and on a slow one it lags behind. It cannot reduce network requests, because the deferred value still changes with every keystroke once rendering catches up. It also can show stale content (compare value !== deferredValue to dim the list).
Typical combination. Use a debounced value as the key of a data request (to limit requests), and useDeferredValue or a transition when displaying large results (to keep typing smooth). For expensive lists, fix rendering first (memo, virtualization), then defer.
Rules of thumb: network or storage cost, so debounce. Continuous events needing regular updates, so throttle. Slow rendering of derived UI, so useDeferredValue or startTransition. Make sure the deferred child is memoized, or it will re-render with the urgent updates anyway.
The example counts how many times a results component renders for the same typing with immediate, deferred and debounced values.
The check typed three characters in separate steps without pausing for the debounce time, and then waited. The debounced component renders only for the final text, because each keystroke restarts the timer. The deferred component rendered every value here, because act finished each keystroke completely before the next one. Deferred renders are abandoned only when keystrokes arrive faster than a deferred render can finish. Output of the run:
immediate results rendered for ""
deferred results rendered for ""
debounced results rendered for ""
immediate results rendered for "r"
deferred results rendered for "r"
immediate results rendered for "re"
deferred results rendered for "re"
immediate results rendered for "rea"
deferred results rendered for "rea"
--- typing finished, waiting
debounced results rendered for "rea"
--- done
Key points
Debounce waits for a quiet period. Throttle limits frequency. Both are timing-based.
useDeferredValue is priority-based: no fixed delay, and unfinished renders are abandoned.
Debounce reduces network requests. useDeferredValue helps with slow rendering.
Combine them when you have both costs, and memoize the deferred child.
Check value !== deferredValue to show a stale-content indicator.
Common mistakes
Using useDeferredValue to reduce network requests.
Forgetting to memoize the child that receives the deferred value.
Using a long debounce on fast, local filtering.
Debouncing without cancelling the previous timer in cleanup.
Showing stale results without any indicator.
Follow-ups
How would you combine a debounced request key with a deferred rendering of results?
What is the difference between a transition and useDeferredValue?
How do you test debounced behaviour with fake timers?
Tips
Separate the problems: request count, update frequency and render cost.
Say useDeferredValue is priority-based, not time-based.
Mention memoizing the child.
140.react-0140Hardsenior
How does Suspense work internally with promises and use(), and why must the promise be cached across renders?
When a component calls use(promise) with a pending promise, React stops rendering that component, shows the nearest Suspense fallback, and attaches a listener to the promise. When it settles, React retries the render. use then returns the value, or throws the rejection to an error boundary. A new promise created on every render would never settle in time, so the promise must come from a stable source: a cache, a loader, a Server Component or a parent that created it once.
Full answer
Suspense lets a component say "I am not ready" while rendering. Older libraries did it by throwing a promise from the render function. In React 19 the supported way is use(promise).
Flow. Render starts. The component calls use(promise). If the promise is pending, React interrupts that component (the rest of the render of that subtree is abandoned), walks up to the nearest <Suspense> boundary and commits its fallback. React keeps track of the promise and subscribes to it. When the promise resolves, React schedules a retry of the suspended render. This time use finds the value and returns it synchronously (React records the promise's status and value on the promise object), the component renders, and the boundary reveals its content. If the promise rejects, use throws the error to the nearest error boundary.
Caching requirement. Each time React retries, it calls your component again. If the component creates the promise itself (use(fetch(...))), each retry creates a new pending promise and suspends again, in an endless loop. The promise must have a stable identity across renders: created in a parent or route loader and passed down, stored in a cache keyed by the request (module-level Map, a data library, a framework cache function), or created in a Server Component (where async/await works). State and refs are not reliable for this, because state of a suspended component that never mounted is not preserved.
Details: libraries mark promises with status fields so that already resolved values can be read synchronously. use can be called conditionally, unlike other hooks, and can also read context. Transitions keep existing content on screen while a retry happens, instead of falling back. React also uses a timing heuristic to avoid flashing fallbacks for very fast resolutions.
The example caches promises by key and counts how many times the component tried to render.
jsx
import { Suspense, use } from 'react';
const cache = new Map();
function fetchCourse(id) {
if (!cache.has(id)) {
console.log('starting request for course ' + id);
cache.set(id, new Promise((resolve) => setTimeout(() => resolve('Course ' + id + ' loaded'), 30)));
}
return cache.get(id);
}
let attempts = 0;
function Course({ id }) {
attempts += 1;
console.log('Course render attempt ' + attempts);
return <p>{use(fetchCourse(id))}</p>;
}
export default function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Course id={7} />
</Suspense>
);
}
The cache makes fetchCourse return the same promise on every attempt, so the request starts once. Attempt 1 suspends. Attempts 2 and 3 are retries after the promise settled, and the request started only once. Without the cache each attempt would start a new request. Output of the run:
Course render attempt 1
starting request for course 7
Course render attempt 2
Course render attempt 3
Key points
A pending use(promise) interrupts the render, shows the nearest fallback and subscribes to the promise.
When the promise settles, React retries the render, and use returns the value or throws the error.
The promise needs a stable identity: cache, loader, parent or Server Component.
Creating the promise inside the suspending component causes an endless loop.
Transitions keep visible content instead of showing the fallback again.
Common mistakes
Calling use(fetch(url)) directly in a component.
Keeping the promise in the state of the component that suspends.
Forgetting an error boundary for rejected promises.
Using Suspense without a transition for updates and flashing fallbacks.
Treating Suspense as a data fetching library rather than a coordination tool.
Follow-ups
How do frameworks create stable promises for Server Components and client components?
What does React do when a transition suspends?
How does a rejected promise reach an error boundary?
Tips
Describe the flow: pending, fallback, subscribe, retry.