Employer interviews
Interviews are private. Sign in to see your group interviews.
Sign in…
This interview was not found. Maybe the data in this browser was cleared.
Interviews dashboardEasy questions are at the top, and harder ones sit under their basic question. If a basic question gets a weak score, the questions under it fade.
1. Index as the key in the cart list
React fundamentals· in roadmap
Question: On the cart page of our online shop, each row has a text box for a gift note. The user can remove a row. Here is the code:
import { useState } from 'react';
type CartItem = { productId: string; name: string };
function CartRow({ item, onRemove }: { item: CartItem; onRemove: () => void }) {
const [note, setNote] = useState('');
return (
<li>
{item.name}
<input value={note} onChange={e => setNote(e.target.value)} placeholder="Gift note" />
<button onClick={onRemove}>Remove</button>
</li>
);
}
export function Cart({ items, onRemove }: { items: CartItem[]; onRemove: (id: string) => void }) {
return (
<ul>
{items.map((item, index) => (
<CartRow key={index} item={item} onRemove={() => onRemove(item.productId)} />
))}
</ul>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: The key is the index. React uses the key to decide which component in the new render is the same one as before. When a row is removed or the list is reordered, the indexes move, so the state of each row (the gift note) stays with the position, not with the product. The fix is a stable id from the data: key equal to item.productId.
Hint (if the candidate says there is no problem): A user has shoes, a hat and a bag in the cart. She writes “Happy birthday” as the note for the shoes. Then she removes the shoes. Now the note “Happy birthday” is next to the hat.
Why does this happen? (step by step)
- Before the removal, the rows are: key 0 shoes, key 1 hat, key 2 bag. The note “Happy birthday” is state inside the component with key 0.
- After the removal, the new list is: key 0 hat, key 1 bag.
- React compares by key. It sees key 0 again, so it thinks it is the same component. It keeps its state and only gives it new props (the hat).
- Key 2 is gone, so React removes the last component, the one that belonged to the bag.
- The result: the hat shows the note of the shoes, and the empty note of the bag is lost.
The fix:
{items.map(item => (
<CartRow key={item.productId} item={item} onRemove={() => onRemove(item.productId)} />
))}
- Now the shoes have the key “shoes” for their whole life. When they are removed, React removes exactly that component and its state.
- Keys must be unique only among siblings, not in the whole app.
- Where the note lives is also a design question. If the note must be sent with the order, it is better to keep it in the cart data (lifted state), not only inside the row.
Follow-up question: What if the items have no id, for example rows the user adds by hand? Can we use Math.random or crypto.randomUUID as the key?
Follow-up answer:
- Not during render. A new key on every render means React removes and creates every row on every render. State is lost, focus is lost, and it is slow.
- Make the id once, when the item is created, for example with crypto.randomUUID in the add handler, and store it in the data.
- The index is fine only when the list never changes order, nothing is added or removed in the middle, and the rows have no state of their own.
Red flag: Says “the key is only there to remove the console warning”, or suggests a random key made during render.
Show answer
2. Pushing into a state array
React fundamentals· in roadmap
Question: On the product page, the user can save products to a wishlist. A junior developer wrote this:
import { useState } from 'react';
export function Wishlist() {
const [items, setItems] = useState<string[]>([]);
function handleSave(productId: string) {
items.push(productId);
setItems(items);
}
return (
<>
<p>{items.length} saved products</p>
<button onClick={() => handleSave('shoes-42')}>Save shoes</button>
</>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: The code changes (mutates) the array that is already in state, then passes the same array to setItems. React compares the old and the new value with Object.is. It is the same object, so React thinks nothing changed and can skip the render. The fix is a new array: setItems with an updater that returns the old items plus the new one.
Hint (if the candidate says there is no problem): The user clicks “Save shoes” three times. The text still says “0 saved products”. Later, when something else on the page renders this component again, the number suddenly jumps to 3.
Why does this happen? (step by step)
- The push method adds the id to the existing array. The array in state is now changed, but React does not know it.
- The setItems call gets the same array reference that React already has.
- Object.is says the old and new values are equal, so React bails out and does not update the screen.
- The data is still changed in memory. So the next render that happens for any other reason shows all the hidden changes at once.
- Other tools that compare references, like memo, useMemo and effect dependencies, also miss the change.
The fix:
function handleSave(productId: string) {
setItems(prev => [...prev, productId]); // a new array
}
- The spread makes a new array, so Object.is sees a change and React renders.
- The updater function also uses the latest value, so several quick clicks are all counted.
- The same rule applies to objects: make a new object with spread, do not change a field in place.
- Methods that change an array in place are push, pop, splice, sort and reverse. Use the spread, filter, map, slice or toSorted methods instead.
Follow-up question: The cart is an array of objects. A teammate writes: find the item, add one to its quantity in place, then call setCart with a spread of the cart. A new array is passed, so is this fine now?
Follow-up answer:
- The page will update, because the array is new. But the item object is still mutated.
- The old snapshot is changed too. Anything that kept the old state (an undo feature, or a previous value kept in a ref) now sees wrong data.
- A memo row component gets the same item object as before, so it is skipped and still shows the old quantity.
- The right way: use the map method and return a new object only for the changed item. For deep data, a library like Immer lets you write “mutating” code that really makes new objects.
Red flag: Says “React compares the content, so it is fine”, or thinks the fix is to force an update instead of making a new array.
Show answer
3. Calling set twice in one click
React fundamentals· in roadmap
Question: The product page has a quantity stepper with a “+2” button for a quick bulk order. Here is the code:
import { useState } from 'react';
export function QuantityStepper() {
const [count, setCount] = useState(1);
function addTwo() {
setCount(count + 1);
setCount(count + 1);
}
return (
<div>
<span>{count}</span>
<button onClick={addTwo}>+2</button>
</div>
);
}
The user clicks “+2” once. What does the screen show, and why?
Short answer: It shows 2, not 3. In this render count is 1, and it stays 1 until the handler ends. Both calls say “make the next value 1 + 1”. React batches them and renders once with 2. When the new value depends on the old one, call set two times with an updater function that adds one to the previous value.
Why does this happen? (step by step)
- The click happens during the render where count is 1. The handler is a closure over that render, so count is the number 1 for the whole handler.
- The first call queues “set to 2”. It does not change the count variable.
- The second call also computes 1 + 1 and queues “set to 2” again.
- React batches all updates of one event and renders once after the handler ends. The last queued value is 2.
The fix:
function addTwo() {
setCount(c => c + 1); // 1 -> 2
setCount(c => c + 1); // 2 -> 3
}
- An updater function gets the value after all earlier queued updates. So the second one sees 2 and returns 3.
- Another simple option: call setCount once with count plus 2. It is clear here because there is only one update.
- A good habit: when the next value depends on the previous value, use an updater.
Follow-up question: What if the two calls are inside a setTimeout, or after an await? Is the result different?
Follow-up answer:
- Since React 18, batching is automatic also inside timeouts, promises and native event handlers. So there is still one render.
- More important: count is still the value from the render where the handler was created. Even after an await, count is 1, so the result is still 2.
- The updater version gives 3 everywhere.
- The same reason explains why console.log right after a set call shows the old value.
Red flag: Says “set is async, so put await before it”. The set function returns nothing to await. The real reason is the snapshot of state in each render.
Show answer
4. A component defined inside another component
React fundamentals· in roadmap
Question: This is part of the checkout page. The developer moved the address field into its own small component to keep the page tidy:
import { useState } from 'react';
export function CheckoutPage() {
const [address, setAddress] = useState('');
const [coupon, setCoupon] = useState('');
function AddressField() {
return (
<label>
Address
<input value={address} onChange={e => setAddress(e.target.value)} />
</label>
);
}
return (
<form>
<AddressField />
<input value={coupon} onChange={e => setCoupon(e.target.value)} placeholder="Coupon" />
<button type="submit">Pay</button>
</form>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: AddressField is defined inside CheckoutPage, so every render of CheckoutPage makes a new function, which React sees as a new component type. React then removes the old AddressField with its DOM and creates a new one. The input tag is replaced on every key press, so it loses focus. The fix: define AddressField at the top level of the file and pass the value and the change handler as props.
Hint (if the candidate says there is no problem): In the address field, the user types one letter and then the cursor is gone. She must click the field again for every letter. The coupon field works fine.
Why does this happen? (step by step)
- The user types a letter. setAddress is called, so CheckoutPage renders again.
- During this render, the line that defines AddressField runs again and makes a new function object.
- React compares the element type at the same position: the old AddressField function and the new one are different objects.
- A different type means “this is a different component”. React unmounts the old one (its DOM and its state are thrown away) and mounts the new one.
- The new input tag is a fresh DOM node. The focus was on the old node, which is gone.
- The coupon input is written directly in the JSX of CheckoutPage, so its type is always the string “input”, and React only updates its value.
The fix:
type AddressFieldProps = { value: string; onChange: (value: string) => void };
function AddressField({ value, onChange }: AddressFieldProps) {
return (
<label>
Address
<input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
// inside CheckoutPage:
// <AddressField value={address} onChange={setAddress} />
- Now AddressField is created once, when the file loads. Its type is the same in every render.
- React keeps the same DOM node and only changes its value, so focus stays.
- The cost: you pass a few props. That is a good thing, because the data flow is now visible.
Follow-up question: A teammate suggests keeping AddressField inside, but wrapping it with useCallback so the function stays the same. Does that work?
Follow-up answer:
- With address in the dependency array, useCallback returns a new function every time address changes, which is every key press. So the bug stays.
- With an empty dependency array, the function stays the same, but it closes over the first address value (a stale closure). The input would always show an empty string.
- So no. A component type must be stable. Define components at the top level of a module.
- If the goal is only to split long JSX, a plain helper that returns JSX and is called like a function (not used as a tag) also works, because no new component type is made. But a separate top-level component is clearer.
Red flag: Blames the browser and suggests adding autoFocus or calling focus in an effect after every render.
Show answer
5. A phone field that starts as undefined
React fundamentals· in roadmap
Question: On the shipping step of checkout, we show the phone number of the customer so they can change it. New customers have no phone number yet. Here is the code:
import { useState } from 'react';
type Customer = { id: string; name: string; phone?: string };
export function ShippingPhone({ customer }: { customer: Customer }) {
const [phone, setPhone] = useState(customer.phone);
return (
<input
type="tel"
value={phone}
onChange={e => setPhone(e.target.value)}
/>
);
}
The TypeScript build passes. You see this in code review. What do you think? Is there a problem?
Short answer: For a new customer, phone is undefined, so the input starts as uncontrolled (React treats value equal to undefined as “no value given”). After the first key press, phone becomes a string and the input becomes controlled. React warns about this switch, because one input must be either controlled or uncontrolled for its whole life. The fix: start with an empty string when customer.phone is missing.
Hint (if the candidate says there is no problem): In development, only for new customers, the console shows a warning when they type the first digit: “A component is changing an uncontrolled input to be controlled.”
Why does this happen? (step by step)
- The phone field in the type is optional, so customer.phone can be undefined.
- useState stores undefined. The type of phone is string or undefined.
- The value attribute accepts undefined in the TypeScript types, so the build does not catch it.
- On the first render, value is undefined. React does not control the input. The browser keeps the value.
- On the first key press, setPhone stores a string. Now value is a string, and React starts to control the input. It warns, because switching mode can lose or confuse the value.
The fix:
const [phone, setPhone] = useState(customer.phone ?? ''); // always a string
- Now value is a string from the first render. The input is controlled the whole time.
- The same rule for checkboxes: the checked attribute must be a boolean from the start, not undefined.
- Do not set both value and defaultValue on one input. Choose one mode.
Follow-up question: The customer data comes from the server. The parent first renders this component with a customer without a phone, and a second later passes the real customer with a phone. What does the field show?
Follow-up answer:
- It still shows the empty value. The argument of useState is used only on the first render. Later changes of the prop do not reach the state.
- Copying a prop into state is the real design problem here.
- Option 1: render the form only after the data is loaded.
- Option 2: give the component key equal to customer.id, so a new customer means a fresh component with fresh state.
- Do not “fix” it with an effect that copies the prop into state on every change. That adds an extra render and can overwrite what the user typed.
Red flag: Wants to hide the warning, or says “it is only a warning, it works”.
Show answer
6. Filtered products kept in state with an effect
Question: The catalog page gets about 500 products from its parent and has a search box. Here is the code:
import { useEffect, useState } from 'react';
type Product = { id: string; name: string; price: number };
export function ProductCatalog({ products }: { products: Product[] }) {
const [query, setQuery] = useState('');
const [filteredProducts, setFilteredProducts] = useState<Product[]>(products);
useEffect(() => {
setFilteredProducts(
products.filter(p => p.name.toLowerCase().includes(query.toLowerCase())),
);
}, [products, query]);
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
<p>{filteredProducts.length} products</p>
<ul>
{filteredProducts.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
</>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: It works, but the effect is not needed. filteredProducts is derived from products and query, so it should be computed during render, not stored in a second state. With the effect, every key press makes two renders and two commits, and the first commit has the old list. The fix: a plain constant computed during render, with useMemo only if measuring shows it is slow.
Hint (if the candidate says there is no problem): In the React DevTools Profiler, every key press shows two commits for ProductCatalog. In the first commit, the input already has the new letter, but the list and the count are still for the old query.
Why does this happen? (step by step)
- The user types a letter. setQuery runs, and React renders with the new query, but filteredProducts is still the old state.
- React commits this render. The list on the page belongs to the old query.
- After the commit, the effect runs and calls setFilteredProducts.
- React renders and commits again, now with the right list.
- So the work doubles, and for a short time the input and the list do not match.
- There is also more code to keep right: if someone forgets a dependency, the two states drift apart.
The fix:
export function ProductCatalog({ products }: { products: Product[] }) {
const [query, setQuery] = useState('');
const filteredProducts = products.filter(p =>
p.name.toLowerCase().includes(query.toLowerCase()),
); // derived during render
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
<p>{filteredProducts.length} products</p>
<ul>
{filteredProducts.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
</>
);
}
- One render per key press. The list and the input always match.
- If the filter is slow (measure it first), wrap it: useMemo with products and query as dependencies.
- The rule: if a value can be computed from props or state, do not put it in state, and do not sync it with an effect.
Follow-up question: Now the products are not in memory. The search must call a server API on each change. Is an effect correct now?
Follow-up answer:
- Yes, now we sync with an outside system (the server), so an effect (or better, a data library) fits.
- We need cleanup: an ignore flag or AbortController, so an old response does not overwrite a newer one.
- We should debounce the query (for example 300 ms), so we do not send one request per letter.
- A library like TanStack Query with the query in the query key handles caching, ordering and retries for us.
Red flag: Thinks useEffect is the place for “anything that should happen when state changes”, or suggests putting useMemo inside the effect.
Show answer
7. An auto-playing product gallery
Question: The product page shows a photo gallery that moves to the next photo every 3 seconds. Most products have 4 to 6 photos. Here is the code:
import { useEffect, useState } from 'react';
export function ProductGallery({ images }: { images: string[] }) {
const [index, setIndex] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setIndex((index + 1) % images.length);
}, 3000);
return () => clearInterval(id);
}, []);
return <img src={images[index]} alt={`Product photo ${index + 1}`} />;
}
You see this in code review. What do you think? Is there a problem?
Short answer: This is a stale closure. The effect runs only once (empty dependency array), so the interval callback was made in the first render, where index is 0. Every 3 seconds it sets the index to 1 again. The gallery moves once and then stops. The fix: an updater function that computes the next index from the previous one, and images.length in the dependency array.
Hint (if the candidate says there is no problem): The gallery shows photo 1, then photo 2 after 3 seconds, and then it stays on photo 2 forever. The eslint rule for hooks shows a warning on the dependency array.
Why does this happen? (step by step)
- First render: index is 0. The effect runs and starts the interval. The callback closes over index 0 and this images array.
- After 3 seconds the callback runs. The next index is 0 plus 1, which is 1, so it calls setIndex with 1. React renders with index 1.
- The effect does not run again, because its dependency array is empty. The interval keeps the old callback.
- After 6 seconds the callback runs again. For it, index is still 0. It sets 1 again. Setting the same value changes nothing.
- This repeats forever. Each render has its own index, but the interval only knows the first one.
The fix:
useEffect(() => {
const id = setInterval(() => {
setIndex(i => (i + 1) % images.length); // React passes the latest index
}, 3000);
return () => clearInterval(id);
}, [images.length]);
- The updater function gets the latest index from React, so the callback does not need to read index from the closure.
- images.length is still read from the closure, so it goes into the dependency array. If a product with a different number of photos is shown, the interval restarts with the right length.
- If the new product has fewer photos, index may be too big for a moment. A simple guard: use the remainder of index divided by the number of images, or reset the gallery with key equal to the product id.
- The cleanup stops the old interval. Without it, every restart would add one more interval.
Follow-up question: Product managers want the gallery to pause while the user hovers over it. The effect must read the latest “paused” value on each tick, but you do not want to restart the interval every time the mouse moves in or out. How?
Follow-up answer:
- Option 1: the useEffectEvent hook (stable since React 19.2). You create an effect event that reads paused and calls setIndex, and you call it from the interval. It always sees the latest values and does not need to be a dependency.
- Option 2: keep paused in a ref (useRef) that is updated in the mouse event handlers. The interval reads ref.current. Refs do not cause renders.
- Option 3: simply put paused in the dependency array and accept that the interval restarts. For a gallery this is often good enough.
- Also check accessibility: moving content that starts by itself should have a visible way to pause it.
Red flag: Silences the lint rule, or removes the dependency array so the effect runs after every render without understanding why that “fixes” it.
Show answer
8. Product details fetched in an effect
Question: On the catalog page, the product list is on the left and the details of the selected product are on the right. Many of our users are on mobile networks. Here is the details component:
import { useEffect, useState } from 'react';
type Product = { id: string; name: string; price: number };
export function ProductDetails({ productId }: { productId: string }) {
const [product, setProduct] = useState<Product | null>(null);
useEffect(() => {
fetch(`/api/products/${productId}`)
.then(res => res.json())
.then((data: Product) => setProduct(data));
}, [productId]);
if (!product) return <p>Loading...</p>;
return (
<section>
<h2>{product.name}</h2>
<p>${product.price}</p>
</section>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: There is a race condition. Every change of productId starts a new request, but old requests are not cancelled or ignored. Responses can arrive in any order, so a slow old response can arrive last and overwrite the details of the product the user selected. The fix: a cleanup that aborts the request with AbortController (or sets an ignore flag), so only the latest response is used. In a real app, a data library like TanStack Query or a framework loader is usually the better choice.
Hint (if the candidate says there is no problem): On a slow network, the user clicks “Shoes” and then quickly “Hat”. The list shows “Hat” as selected, but the details panel shows “Shoes”. On office Wi-Fi nobody can reproduce it.
Why does this happen? (step by step)
- The user clicks “Shoes”. The effect runs and starts request A for shoes.
- Half a second later, the user clicks “Hat”. productId changes, the effect runs again and starts request B for hat. Request A is still running.
- The network is not a queue. Request B is small or hits a cache and returns first. setProduct is called with the hat.
- Then request A returns. Nothing stops it, so it calls setProduct with the shoes.
- The last write wins: the panel shows shoes while hat is selected.
- There are smaller problems too: no check of res.ok, no error handling, and while the new product loads, the old product is still shown.
The fix:
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const res = await fetch(`/api/products/${productId}`, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data: Product = await res.json();
if (!controller.signal.aborted) setProduct(data);
} catch (err) {
if (!controller.signal.aborted) console.error(err); // show an error state here
}
}
load();
return () => controller.abort(); // runs before the next effect and on unmount
}, [productId]);
- When productId changes, React first runs the cleanup of the old effect. It aborts request A.
- An aborted fetch rejects, and the check of signal.aborted makes sure no old data is written.
- Abort also stops the network transfer, which saves data on mobile.
- To avoid showing the old product while the new one loads, the parent can render the component with key equal to productId. Then the state starts fresh for each product.
Follow-up question: Why do many teams use TanStack Query (or a framework loader) instead of writing this effect?
Follow-up answer:
import { useQuery } from '@tanstack/react-query';
async function fetchProduct(id: string, signal: AbortSignal): Promise<Product> {
const res = await fetch(`/api/products/${id}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
export function ProductDetails({ productId }: { productId: string }) {
const { data, isPending, error } = useQuery({
queryKey: ['product', productId],
queryFn: ({ signal }) => fetchProduct(productId, signal),
});
if (isPending) return <p>Loading...</p>;
if (error) return <p>Could not load the product.</p>;
return <h2>{data.name}</h2>;
}
- Data is stored per query key. The component shows the data for the current productId, so a late response for another id cannot replace it.
- Caching: going back to “Shoes” shows it at once, and it can refresh in the background.
- It removes duplicate requests, retries failed ones, and gives loading and error states.
- The same effect code, written by hand in many components, is a common place for bugs.
Red flag: Suggests “disable the list while loading” or a debounce as the only fix, or writes useEffect with an async function directly (the effect must return a cleanup function, not a promise).
Show answer
9. A hook after an early return
Question: The product page gets the product from its parent. While the product loads, the prop is null. Here is the code:
import { useState } from 'react';
type Product = { id: string; name: string; price: number };
export function ProductPage({ product }: { product: Product | null }) {
if (!product) return <p>Loading...</p>;
const [quantity, setQuantity] = useState(1);
return (
<section>
<h1>{product.name}</h1>
<button onClick={() => setQuantity(q => q + 1)}>Quantity: {quantity}</button>
</section>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: useState is called after an early return, so it is called only in some renders. This breaks the rules of hooks. React finds each hook’s data by its call order in the component. When the product arrives, the component calls one more hook than in the last render, and React throws an error. The fix: call all hooks at the top, before any return, or move the loaded part into its own component.
Hint (if the candidate says there is no problem): The page shows “Loading…”, and then, the moment the product arrives, it crashes with the error “Rendered more hooks than during the previous render.” The lint rule for hooks also marks this line.
Why does this happen? (step by step)
- React does not know hook names. For each component it keeps a list of hook slots, and it matches hooks to slots by the order in which they are called.
- First render: product is null. The function returns early. Zero hooks are called.
- Next render: the product is here. Now useState is called. React expected the same number of hooks as last time, but gets more, so it throws.
- The same idea explains hooks inside an if or a loop: if the number or order of calls changes, a hook can read the slot of another hook.
The fix:
export function ProductPage({ product }: { product: Product | null }) {
const [quantity, setQuantity] = useState(1); // always called
if (!product) return <p>Loading...</p>;
return (
<section>
<h1>{product.name}</h1>
<button onClick={() => setQuantity(q => q + 1)}>Quantity: {quantity}</button>
</section>
);
}
- All hooks run on every render, in the same order. The early return comes after them.
- Often a cleaner design: a small wrapper shows “Loading…” and renders a ProductDetails component only when the product exists. ProductDetails can then use hooks freely, and its props are never null.
- Keep the eslint-plugin-react-hooks rules on. They catch this at write time.
Follow-up question: We want a “favorite” button with its own state, but only for logged-in users. How do you do that without a conditional hook?
Follow-up answer:
- Put the button and its state in its own component, and render that component conditionally: when there is a user, render the FavoriteButton component.
- Rendering a component conditionally is fine. Each component instance has its own list of hooks. When it is not rendered, its whole list is simply not there.
- What is not allowed is a hook call that sometimes happens inside the same component.
Red flag: Says “it works in my tests”, or wants to turn off the lint rule instead of moving the hook.
Show answer
10. A memo grid that renders every time
React hooks· in roadmapWeb performance· in roadmap
Question: The shop page shows about 500 product cards. The grid was slow, so a developer wrapped it in memo. Here is the code:
import { memo, useState } from 'react';
type Product = { id: string; name: string; price: number };
type GridOptions = { showPrices: boolean; currency: string };
type GridProps = { products: Product[]; options: GridOptions; onAdd: (productId: string) => void };
const ProductGrid = memo(function ProductGrid({ products, options, onAdd }: GridProps) {
return (
<div className="grid">
{products.map(p => (
<article key={p.id}>
<h3>{p.name}</h3>
{options.showPrices && <p>{p.price} {options.currency}</p>}
<button onClick={() => onAdd(p.id)}>Add to cart</button>
</article>
))}
</div>
);
});
export function ShopPage({ products }: { products: Product[] }) {
const [cartIds, setCartIds] = useState<string[]>([]);
return (
<>
<p>Cart: {cartIds.length}</p>
<ProductGrid
products={products}
options={{ showPrices: true, currency: 'USD' }}
onAdd={id => setCartIds(ids => [...ids, id])}
/>
</>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: memo does nothing here. memo skips a render only when every prop is equal by Object.is to the last one. options is a new object literal and onAdd is a new arrow function on every render of ShopPage. So every “Add to cart” click renders all 500 cards again. The fix: make the props stable. Move the constant options out of the component, and wrap onAdd in useCallback.
Hint (if the candidate says there is no problem): In the React DevTools Profiler, every click on “Add to cart” shows ProductGrid rendering again, and it says the reason is that the options and onAdd props changed. On a mid-range phone, each click takes about 100 ms before the cart number changes.
Why does this happen? (step by step)
- A click calls setCartIds, so ShopPage renders again.
- In this render, the JSX creates a new options object and a new onAdd function. They look the same, but they are new objects.
- memo compares each prop with Object.is. products is the same array, but options and onAdd are not the same objects.
- One prop is different, so memo lets the render happen. ProductGrid and all 500 cards render again.
- memo also has a small cost (the comparison). Here we pay it and get nothing back.
The fix:
import { useCallback, useState } from 'react';
const GRID_OPTIONS: GridOptions = { showPrices: true, currency: 'USD' }; // made once
export function ShopPage({ products }: { products: Product[] }) {
const [cartIds, setCartIds] = useState<string[]>([]);
const handleAdd = useCallback((id: string) => {
setCartIds(ids => [...ids, id]);
}, []); // the set function is stable, so no dependencies
return (
<>
<p>Cart: {cartIds.length}</p>
<ProductGrid products={products} options={GRID_OPTIONS} onAdd={handleAdd} />
</>
);
}
- GRID_OPTIONS is created once when the module loads. If the options depend on props or state, use useMemo instead.
- useCallback returns the same function while its dependencies do not change. The updater form means we do not need cartIds as a dependency.
- Another option: pass simple values (showPrices and currency as two props) instead of an object. Strings and booleans compare by value.
- Measure before and after. The React Compiler, an optional build tool, can add this memoization for you.
Follow-up question: Later someone writes the grid as ProductGrid with a Banner component inside it as children, between the opening and closing tags. The props for the grid are all stable. Does memo work now?
Follow-up answer:
- No. The children prop is JSX, and JSX creates a new element object on every render. So children is a new prop each time, and memo renders again.
- Fixes: create the element once with useMemo, or move the banner out of the memo component, or let the grid render the banner itself.
- The general lesson: memo only helps when every prop is stable. Check all of them, including children.
Red flag: Thinks memo compares props deeply, or wants to wrap every component and every value in memo, useMemo and useCallback without measuring.
Show answer
11. One big app context
React hooks· in roadmapWeb performance· in roadmap
Question: To avoid passing props, the team put all shared data of the shop in one context:
import { createContext, useContext, useState, type Dispatch, type ReactNode, type SetStateAction } from 'react';
type CartItem = { productId: string; quantity: number };
type User = { id: string; name: string };
type AppState = { cart: CartItem[]; user: User | null; theme: 'light' | 'dark' };
type AppContextValue = { state: AppState; setState: Dispatch<SetStateAction<AppState>> };
const AppContext = createContext<AppContextValue | null>(null);
export function AppProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<AppState>({ cart: [], user: null, theme: 'light' });
return <AppContext value={{ state, setState }}>{children}</AppContext>;
}
export function useApp() {
const ctx = useContext(AppContext);
if (!ctx) throw new Error('useApp must be used inside AppProvider');
return ctx;
}
About 300 components call useApp: the header, the filters, the footer, and each of the 200 product cards on the page (the cards read the theme and call setState to add to the cart). The cards are wrapped in memo. You see this in code review. What do you think? Is there a problem?
Short answer: Every component that reads a context renders again when the context value changes, and memo does not stop this. Here the value is one object with everything in it, and it is also a new object on every render of the provider. So adding one item to the cart renders all 300 readers, including 200 cards that only need the theme. The fix: split the context by how often data changes (cart, user, theme), keep each value stable with useMemo, and separate the stable actions from the changing data.
Hint (if the candidate says there is no problem): In the Profiler, one click on “Add to cart” renders about 300 components, including all product cards. On low-end Android phones, the INP of this click in our field data is about 400 ms.
Why does this happen? (step by step)
- A click calls setState with a new cart. The state object is new, so AppProvider renders again.
- The JSX creates a new value object: an object with state and setState. Object.is says it is different from the last one.
- React finds every component that called useContext for AppContext and schedules a render for each, even if the part they use (the theme) did not change.
- memo only compares props. A context change goes around it, so the memo cards still render.
- Good news: the children prop of AppProvider is the same element as before, so components that do not read the context are not rendered. The cost comes only from the readers, but here almost everyone is a reader.
The fix:
import { createContext, useMemo, useState, type ReactNode } from 'react';
type CartItem = { productId: string; quantity: number };
type CartActions = { addToCart: (productId: string) => void };
export const CartItemsContext = createContext<CartItem[]>([]);
export const CartActionsContext = createContext<CartActions | null>(null);
export const ThemeContext = createContext<'light' | 'dark'>('light');
export function CartProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<CartItem[]>([]);
const actions = useMemo<CartActions>(() => ({
addToCart: productId => setItems(prev => [...prev, { productId, quantity: 1 }]),
}), []); // setItems is stable, so actions never change
return (
<CartActionsContext value={actions}>
<CartItemsContext value={items}>{children}</CartItemsContext>
</CartActionsContext>
);
}
- A product card now reads only ThemeContext and CartActionsContext. Neither changes when the cart changes, so the cards do not render.
- Only the components that show the cart (the cart badge, the mini cart) read CartItemsContext.
- Each value is stable: items is the state itself, and actions is made once.
- The user and the theme get their own providers, which change rarely.
Follow-up question: The cart grows. Some components need only the item count, others need the total price. With a context, all of them render on every cart change. What else can you do?
Follow-up answer:
- Use an external store with selectors, for example Zustand or Redux Toolkit with useSelector. They are built on useSyncExternalStore.
- Each component subscribes with a selector, like “the number of items”. The store calls the selector after each change, and the component renders only if the selected value changed.
- Server data (products, prices) usually belongs in a server-state library like TanStack Query, not in a global client store.
- Context is still great for values that change rarely: theme, current user, language.
Red flag: Says “context is slow, never use it”, or thinks wrapping the cards in memo will fix it.
Show answer
12. A checkout form that can be sent twice
Question: This is the last step of checkout. The payment request usually takes 3 to 5 seconds. Here is the code:
import { useState, type FormEvent } from 'react';
export function CheckoutForm() {
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const res = await fetch('/api/orders', { method: 'POST', body: formData });
if (!res.ok) setError('Payment failed. Please try again.');
else window.location.assign('/thank-you');
}
return (
<form onSubmit={handleSubmit}>
<input name="address" required />
<button type="submit">Pay $49</button>
{error && <p role="alert">{error}</p>}
</form>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: Nothing stops a second submit while the first request is still running, and the user gets no feedback that payment is in progress. A user who clicks again sends a second order. On the client, a React 19 form action with useActionState and a submit button that uses useFormStatus gives a pending state, so the button is disabled and shows “Paying…”. But the real protection must be on the server: send an idempotency key with the order, so the same checkout is never charged twice. Also, a network error is not handled at all.
Hint (if the candidate says there is no problem): Support gets emails from customers who were charged twice. The server logs show two POST requests to /api/orders from the same user, about one second apart.
Why does this happen? (step by step)
- The user clicks “Pay”. The request starts and takes several seconds.
- The button looks the same and is still enabled. Nothing on the screen says “wait”.
- The user thinks the click did not work and clicks again. A second request starts.
- The server sees two independent orders and charges two times.
- If fetch itself fails (for example the network drops), the promise rejects, the error is not caught, and the user sees nothing.
The fix:
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
type CheckoutState = { error: string | null };
async function placeOrder(_prev: CheckoutState, formData: FormData): Promise<CheckoutState> {
try {
const res = await fetch('/api/orders', { method: 'POST', body: formData });
if (!res.ok) return { error: 'Payment failed. Please try again.' };
} catch {
return { error: 'Network error. Please check your connection.' };
}
window.location.assign('/thank-you');
return { error: null };
}
function PayButton() {
const { pending } = useFormStatus(); // status of the parent form
return <button type="submit" disabled={pending}>{pending ? 'Paying...' : 'Pay $49'}</button>;
}
export function CheckoutForm({ checkoutId }: { checkoutId: string }) {
const [state, formAction] = useActionState(placeOrder, { error: null });
return (
<form action={formAction}>
<input type="hidden" name="idempotencyKey" value={checkoutId} />
<input name="address" required />
<PayButton />
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}
- The form action runs placeOrder inside a transition. React tracks it as pending until it finishes.
- PayButton is inside the form, so useFormStatus sees that the form is pending. The button is disabled and shows “Paying…”.
- The result of the action (an error message or nothing) is the state of useActionState.
- checkoutId is created on the server when checkout starts. The server stores it with the order. A second request with the same key returns the first result and does not charge again.
- The button is good UX, but it is not a guarantee. A user can open two tabs or reload, and a network layer can retry a request. Only the server can make the payment safe.
Follow-up question: Why is PayButton a separate component? Could you use the pending value in CheckoutForm itself?
Follow-up answer:
- useFormStatus reads the status of the form that contains the component. Called in CheckoutForm, which renders the form, it does not see that form, so pending is always false.
- Yes, there is another way: useActionState returns a third value, isPending. CheckoutForm can use it directly to disable the button.
- useFormStatus is handy for reusable buttons (a design-system submit button) that do not know which action the form has.
Red flag: Only says “disable the button” and does not mention the server, or thinks the browser blocks double submits by itself.
Show answer
13. Search over 10,000 products while typing
React hooks· in roadmapWeb performance· in roadmap
Question: Our shop loads its full catalog of about 10,000 products into the browser, so search works without a server. Many customers use mid-range Android phones. Here is the search page:
import { useState } from 'react';
type Product = { id: string; name: string; price: number; imageUrl: string };
function ProductRow({ product }: { product: Product }) {
return (
<li className="product-row">
<img src={product.imageUrl} alt="" width={48} height={48} />
<span>{product.name}</span>
<span>${product.price.toFixed(2)}</span>
</li>
);
}
export function ProductSearch({ products }: { products: Product[] }) {
const [query, setQuery] = useState('');
const results = products.filter(p => p.name.toLowerCase().includes(query.toLowerCase()));
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
<p>{results.length} results</p>
<ul>
{results.map(p => <ProductRow key={p.id} product={p} />)}
</ul>
</>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: Every key press renders the whole result list in one urgent update. With an empty or short query, that is up to 10,000 rows to render and commit before the input can show the next letter, so typing freezes. Filtering is usually the small part. Rendering and committing thousands of rows is the big part. Fixes, in order: measure; keep the input urgent and render the list with a deferred value (useDeferredValue plus a memo list); render fewer rows (a limit, pagination or virtualisation); and only then make the filter itself cheaper.
Hint (if the candidate says there is no problem): On a fast laptop it feels fine. On a mid-range phone, letters appear in bursts, and our field data shows INP at the 75th percentile of about 600 ms on this page. A good INP is 200 ms or less.
Why does this happen? (step by step)
- The user types a letter. setQuery is an urgent update.
- React renders ProductSearch. It filters 10,000 names and creates one ProductRow element for every match.
- With a short query, most products match. React renders thousands of rows and then commits thousands of DOM changes, all in one task.
- The browser cannot paint the new letter until this task ends. On a slow CPU this takes hundreds of milliseconds.
- The next key press waits in line, so the input feels stuck.
The fix, step 1: measure. Use the Performance panel with CPU throttling and the React DevTools Profiler. See how much time is filtering and how much is rendering and committing. Do not guess.
The fix, step 2: keep typing urgent.
import { memo, useDeferredValue, useMemo, useState } from 'react';
const ResultList = memo(function ResultList({ products, query }: { products: Product[]; query: string }) {
const results = useMemo(() => {
const q = query.toLowerCase();
return products.filter(p => p.name.toLowerCase().includes(q));
}, [products, query]);
return (
<>
<p>{results.length} results</p>
<ul>
{results.slice(0, 100).map(p => <ProductRow key={p.id} product={p} />)}
</ul>
</>
);
});
export function ProductSearch({ products }: { products: Product[] }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<ResultList products={products} query={deferredQuery} />
</div>
</>
);
}
- On a key press, React first renders with the new query but the old deferred query. ResultList gets the same props, and memo skips it. This render is fast, so the letter appears at once.
- Then React renders again in the background with the new deferred query. This render can be interrupted: if the user types another letter, React drops it and starts again with the newest value.
- memo is required here. Without it, ResultList would render in the urgent pass too, and nothing would be gained.
- useDeferredValue does not make the list faster. It only stops the list from blocking the input. The list can still lag on slow phones.
The fix, step 3: render fewer rows.
- Nobody reads 10,000 rows. Show the first 100 results with a “show more” button, or use pagination.
- Or use virtualisation (for example TanStack Virtual or react-window): only the rows that are visible in the scroll area are rendered, about 20 to 30, whatever the number of results.
- Trade-offs of virtualisation: the browser’s find-in-page does not see rows that are not rendered, screen readers see only rendered rows, rows of different heights need extra work, and scroll position must be handled when the user comes back.
The fix, step 4: a cheaper filter (only if measuring shows it matters). Precompute the lowercase names once. For a much bigger catalog, or for typo-tolerant search, move the search to the server and debounce the requests.
About useTransition and debounce: useTransition is an option when you control the setter: keep the input state urgent, and update a second “filter query” state inside startTransition. Never put the input’s own value in a transition, or the input itself becomes slow. A debounce waits a fixed time even on fast devices, and when it fires, the big render still blocks. Debounce is still the right tool for network requests.
Follow-up question: You shipped the fix. How do you prove it helped real users?
Follow-up answer:
- In the lab: record the same typing in the Performance panel with CPU throttling, before and after. Compare the long tasks and the time to the next paint.
- In the field: collect INP from real users (for example with the web-vitals library) and look at the 75th percentile for this page, split by device type. The goal is 200 ms or less.
- Watch for regressions: a test or a budget that fails if the search page gets slower again.
Red flag: Says “add a debounce” or “wrap the filter in useMemo” and stops there, without seeing that rendering thousands of rows is the main cost; or moves the filter to a Web Worker before measuring.
Show answer
14. Where should each piece of state live?
React fundamentals· in roadmapReact hooks· in roadmap
Question: We are rebuilding the product pages of our shop in React 19. The pages have:
- A product list with filters (category, price range), sorting and pages. Marketing shares links to filtered lists, for example “all shoes under $50”.
- A product details page with reviews.
- A search box in the header.
- A cart that is shown on every page. Logged-in users expect the same cart on their phone and laptop.
- A checkout form with address and payment.
- Small UI things: an open filter drawer, a selected photo in the gallery.
The team proposes to put everything in one global Redux store and to load all server data into it with effects. Where should each piece of state live? Explain your design step by step.
Short answer: Not all state is the same, so it should not all live in one place. Sort it by who owns it: server state (products, details, reviews, the saved cart) goes into a server-state library like TanStack Query or a framework loader, which handles caching and refetching; URL state (filters, sort, page, search query) goes into the URL so links and the back button work; form state stays in the form (uncontrolled inputs with a React 19 form action); local UI state stays in useState next to where it is used; and only a small amount of real global client state, like the guest cart or the theme, goes into a context or a small store. Derived values are computed during render.
The kinds of state:
- Server state: the server owns it. Our copy can be old. It needs caching, refetching, loading and error states, and protection against out-of-order responses.
- URL state: anything that should survive a reload or be shared as a link.
- Form state: values the user is typing that are not saved yet.
- Local UI state: only one component cares, for example “is the drawer open”.
- Global client state: shared by many distant components and not owned by the server.
- Derived state: can be computed from the others, like the cart total. It should not be stored.
Where each piece goes:
- Product list, details and reviews: TanStack Query (or the loader of a framework like React Router or Next.js). The query key holds everything the data depends on, for example the filters. Writing them into a global store by hand with effects means writing caching and race handling again ourselves.
- Filters, sort, page and search query: URL search params. The URL is the single source of truth. The list reads it, the filter UI writes it. Marketing links work, and the back button undoes a filter change.
- Cart: for logged-in users, the server owns it. Read it with a query and change it with mutations, and invalidate the cart query after each change. Use useOptimistic or the optimistic updates of the library so “Add to cart” feels instant. For guests, keep it in a small client store saved in localStorage, and merge it into the server cart after login.
- Checkout form: local to the form. Uncontrolled inputs plus a form action with useActionState are enough. The server validates everything again and computes the prices. Never trust a price from the client.
- Filter drawer, selected photo: useState in the component that needs it.
- Theme, current user: context, because they change rarely.
import { useSearchParams } from 'react-router';
import { useQuery } from '@tanstack/react-query';
type Product = { id: string; name: string; price: number };
type Filters = { category: string; sort: string; page: number };
async function fetchProducts(filters: Filters, signal: AbortSignal): Promise<Product[]> {
const params = new URLSearchParams({ ...filters, page: String(filters.page) });
const res = await fetch(`/api/products?${params}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
export function ProductListPage() {
const [params, setParams] = useSearchParams();
const filters: Filters = {
category: params.get('category') ?? 'all',
sort: params.get('sort') ?? 'popular',
page: Number(params.get('page') ?? '1'),
};
const { data, isPending } = useQuery({
queryKey: ['products', filters], // new filters, new cache entry
queryFn: ({ signal }) => fetchProducts(filters, signal),
});
function setCategory(category: string) {
setParams(prev => {
const next = new URLSearchParams(prev);
next.set('category', category);
next.set('page', '1'); // a new filter starts at page 1
return next;
});
}
return (
<>
<button onClick={() => setCategory('shoes')}>Shoes</button>
{isPending ? <p>Loading...</p> : <ul>{data?.map(p => <li key={p.id}>{p.name}</li>)}</ul>}
</>
);
}
Trade-offs:
- Two tools instead of one. A server-state library plus URL state is more than “one store”, but each tool does one job well, and the global store becomes small or disappears.
- The URL has limits. Keep only small, shareable values in it, not whole objects. Validate them, because users can edit the URL.
- Optimistic cart updates need a plan for errors: roll back and show a message.
- A global store is still fine for real client state that many parts of the app change, like a multi-step wizard or an editor. The point is not “never Redux”, it is “not server data by hand”.
Follow-up question: A user has the shop open in two tabs and adds a product to the cart in one tab. What does the other tab show, and how do you keep it right?
Follow-up answer:
- Without extra work, the other tab shows the old cart until it fetches again.
- TanStack Query refetches stale queries by default when the window gets focus again, so the cart is fresh when the user switches tabs.
- For a guest cart in localStorage, the storage event fires in the other tabs when the value changes. Listen to it and update the store. A BroadcastChannel is another option.
- At checkout, the server is the final truth: it checks stock and prices again, and the UI shows any change before payment.
Red flag: Copies all server data into a global store with useEffect and handles loading, caching and races by hand everywhere; or keeps filters only in component state, so links and the back button do not work.
Show answer
15. Products copied into a global store
State management in React· in roadmap
Question: The shop keeps its product list in a global Zustand store. Each page loads it like this:
import { useEffect } from 'react';
import { create } from 'zustand';
type Product = { id: string; name: string; price: number };
type ShopStore = {
products: Product[];
loading: boolean;
setProducts: (p: Product[]) => void;
setLoading: (v: boolean) => void;
};
export const useShop = create<ShopStore>()(set => ({
products: [],
loading: false,
setProducts: products => set({ products }),
setLoading: loading => set({ loading }),
}));
export function useProducts() {
const { products, loading, setProducts, setLoading } = useShop();
useEffect(() => {
setLoading(true);
fetch('/api/products')
.then(r => r.json())
.then(setProducts)
.finally(() => setLoading(false));
}, [setProducts, setLoading]);
return { products, loading };
}
The header, the product grid and the sidebar all call useProducts. You see this in code review. What do you think? Is there a problem?
Short answer: Server data is copied by hand into a client store. So the code must do caching, loading, errors and freshness itself, and it does them badly: every component that calls the hook sends its own request, there is no error state, the data never refreshes after a change, and the hook reads the whole store, so every component renders on every store change. Products are server state. They belong in a server-state cache such as TanStack Query (or the router’s loader), keyed by query, with staleTime and invalidation. The global store should keep only real client state, like the cart.
Hint (if the candidate says there is no problem): The Network panel shows three requests to /api/products when the page opens. After an admin changes a price, users see the old price until they reload. Typing in the search box renders the product grid.
Why does this happen? (step by step)
- Three components call useProducts, so three effects run after mount, and each sends a request. Nothing removes duplicates.
- The responses come back in any order and each one replaces the list. If one fails, the error is lost, and loading may become false while another request is still running.
- Nothing marks the data as old. After a price change on the server, the store keeps the old list until a full reload.
useShop()with no selector subscribes to the whole store. Any change, for example a search text stored there, renders every caller.
The fix:
import { useQuery } from '@tanstack/react-query';
type Product = { id: string; name: string; price: number };
export function useProducts() {
return useQuery({
queryKey: ['products'],
queryFn: async (): Promise<Product[]> => {
const res = await fetch('/api/products');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
},
staleTime: 60_000,
});
}
- All callers share the key [‘products’], so there is one request and one cache entry.
- The hook gives data, isPending and error. Failed requests are retried.
- After a mutation,
invalidateQueries({ queryKey: ['products'] })fetches fresh data. The data is also refetched when the user comes back to the tab. - Each component renders only when the query result it uses changes.
Follow-up question: Then what is left for the Zustand store? When is a client store the right tool?
Follow-up answer:
- State that is created in the browser and read in many distant places: the cart before checkout, a multi-step form draft, UI settings.
- Read it with selectors, like
useCart(s => s.items.length), so a component renders only when its part changes. - Filters and search text that people share belong in the URL, not in the store.
Red flag: Says “add a flag so only the first component fetches”, or builds a cache by hand in the store, without seeing that server data needs a server-state tool.
Show answer
16. Every page in one bundle
Routing and code splitting in React· in roadmapWeb performance· in roadmap
Question: This is the router of our shop:
import { createBrowserRouter } from 'react-router';
import ShopLayout from './ShopLayout';
import HomePage from './pages/HomePage';
import ProductPage from './pages/ProductPage';
import CheckoutPage from './pages/CheckoutPage';
import AdminPage from './admin/AdminPage'; // charts + rich editor
export const router = createBrowserRouter([
{
path: '/',
Component: ShopLayout,
children: [
{ index: true, Component: HomePage },
{ path: 'products/:id', Component: ProductPage },
{ path: 'checkout', Component: CheckoutPage },
{ path: 'admin', Component: AdminPage },
],
},
]);
There is no error boundary anywhere. You see this in code review. What do you think? Is there a problem?
Short answer: Two problems. First, every page is imported at the top, so the bundler puts all of them, including the heavy admin page that almost no customer opens, into the first JavaScript file. Every visitor downloads and parses it before the home page works. Split by route with lazy loading (React Router’s lazy route field, or React.lazy with Suspense). Second, with no error boundary, one render error anywhere removes the whole app and leaves a white page. Add an ErrorBoundary per route (at least on the layout), and report the errors.
Hint (if the candidate says there is no problem): The main JavaScript file is 1.4 MB. On a mid-range phone the home page LCP is 4.5 s. Last week a bug in the reviews widget made the product page completely white.
Why does this happen? (step by step)
- A static
importat the top of a file is part of the main module graph. The bundler must include it in the entry chunk. - The admin page imports a chart library and a rich text editor, so they end up in the entry chunk too.
- The browser must download, parse and run all of it before React can render the home page.
- When a component throws during render and there is no error boundary above it, React unmounts the whole root.
The fix:
export const router = createBrowserRouter([
{
path: '/',
Component: ShopLayout,
ErrorBoundary: RootError, // the layout's error page
children: [
{ index: true, Component: HomePage }, // keep the landing page in the main chunk
{ path: 'products/:id', lazy: () => import('./pages/ProductRoute') },
{ path: 'checkout', lazy: () => import('./pages/CheckoutRoute') },
{ path: 'admin', lazy: () => import('./admin/AdminRoute') },
],
},
]);
- Each lazy route module exports its Component (and loader, ErrorBoundary if needed). The bundler makes one chunk per route.
- The home page stays in the main chunk, because almost every visit starts there.
- Prefetch likely next pages, for example the product chunk when a product card is visible or hovered.
- Inside a page, wrap risky widgets (reviews, recommendations) in their own error boundary, so the buy button keeps working.
- Check the result with a bundle analyzer and measure LCP on a real phone.
Follow-up question: After splitting, the product page now shows a spinner for the chunk, then a spinner for the data. How do you fix this?
Follow-up answer:
- This is a waterfall: the chunk loads, then the component starts the fetch.
- Use a route loader (in the same lazy module), so the router loads the code and starts the data request at the same time when navigation starts.
- Prefetch the chunk and the data on hover or when the link is visible.
Red flag: Wants to split every component into its own chunk, or says error boundaries also catch errors in onClick handlers and promises.
Show answer
17. A sale timer on a server-rendered page
SSR and Server Components· in roadmap
Question: The product page is rendered on the server (SSR) and then hydrated. A developer added this badge:
'use client';
export function SaleBadge({ endsAt }: { endsAt: string }) {
const end = new Date(endsAt);
const minutes = Math.round((end.getTime() - Date.now()) / 60_000);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 600;
return (
<p className="sale">
{isMobile ? 'Sale' : 'Big sale'}: ends in {minutes} min
(at {end.toLocaleTimeString()})
</p>
);
}
You see this in code review. What do you think? Is there a problem?
Short answer: The first render in the browser does not produce the same HTML as the server, so hydration fails. Date.now() is different on the two machines, window does not exist on the server (so the server always renders “Big sale”), and toLocaleTimeString uses the time zone and language of the machine, which are the server’s on the server and the user’s in the browser. React reports a hydration error, and the text flashes or the whole part is rendered again on the client. The fix: render something stable on the server and in the first client render, then fill in the browser-only values in an effect after hydration. Use CSS media queries for layout differences instead of window.innerWidth.
Hint (if the candidate says there is no problem): The console shows “Hydration failed because the server rendered text didn’t match the client”. Users in Berlin see a time that is one hour off for a moment, then it jumps.
Why does this happen? (step by step)
- The server renders at 12:00:00 in UTC with language en-US. It has no window, so isMobile is false.
- The HTML reaches a phone in Berlin a moment later. The user sees “Big sale: ends in 30 min (at 12:30:00 PM)”.
- Hydration runs the component again in the browser: a different minute count, isMobile is true, and the time is in Berlin time and German format.
- React compares and finds different text. It cannot trust the server HTML for that part, so it re-renders it on the client. The user sees the text jump.
The fix:
'use client';
import { useEffect, useState } from 'react';
export function SaleBadge({ endsAt }: { endsAt: string }) {
const [now, setNow] = useState<number | null>(null);
useEffect(() => {
setNow(Date.now());
const id = setInterval(() => setNow(Date.now()), 30_000);
return () => clearInterval(id);
}, []);
const end = new Date(endsAt);
let text = ': ends soon';
if (now !== null) {
const minutes = Math.round((end.getTime() - now) / 60_000);
text = `: ends in ${minutes} min (at ${end.toLocaleTimeString()})`;
}
return (
<p className="sale">
<span className="sale-long">Big sale</span>
<span className="sale-short">Sale</span>
{text}
</p>
);
}
- The server and the first client render both show “ends soon”. No mismatch.
- After hydration, the effect sets the real time, and the text updates with the user’s time zone.
- The short or long label is chosen with CSS media queries, so the HTML is the same everywhere.
- suppressHydrationWarning only hides the warning for one element’s text. It is for values that are expected to differ, like a timestamp, and it does not fix layout or logic.
Follow-up question: A product page shows “Welcome back, Sara” for signed-in users. Can you render that on the server without a mismatch?
Follow-up answer:
- Yes, if the server knows the user from the request (a cookie or session) and renders the same thing the client will. Then both sides use the same data.
- Careful with caching: a page with personal data must not be stored in a shared CDN cache. Mark it private, or render the personal part in a separate client or streamed part.
- If the server cannot know (for example data in localStorage), render a neutral placeholder and fill it in after hydration.
Red flag: Turns off SSR for the whole page, or puts suppressHydrationWarning on the root to hide all mismatches.
Show answer
18. Notes of the wrong customer
How React works inside· in roadmap
Question: In the shop admin, a support agent picks a customer from a list on the left and writes notes on the right:
import { useState } from 'react';
type Customer = { id: string; name: string; notes: string };
function NotesEditor({ customer, onSave }: {
customer: Customer;
onSave: (notes: string) => void;
}) {
const [draft, setDraft] = useState(customer.notes);
return (
<form onSubmit={e => { e.preventDefault(); onSave(draft); }}>
<h2>{customer.name}</h2>
<textarea value={draft} onChange={e => setDraft(e.target.value)} />
<button>Save</button>
</form>
);
}
export function SupportPage({ customers }: { customers: Customer[] }) {
const [selected, setSelected] = useState(customers[0]);
return (
<div className="split">
<CustomerList items={customers} onPick={setSelected} />
<NotesEditor customer={selected} onSave={n => saveNotes(selected.id, n)} />
</div>
);
}
Agents report that after picking another customer, the heading changes but the text box still shows the notes of the previous customer. Sometimes they save those notes on the wrong customer. Why? How do you fix it?
Short answer: React keeps state by the component’s place and type in the tree, not by its props. NotesEditor stays at the same place with the same type, so React keeps the same instance and its draft state. useState(customer.notes) uses its argument only on the first render, so the new customer’s notes are ignored. The fix is to give the editor an identity: <NotesEditor key={selected.id} … />. A new key makes React destroy the old editor and create a fresh one with fresh state.
Hint (if the candidate does not see it): Put a console.log in a useEffect with an empty array inside NotesEditor. It logs only once, even after picking five customers.
Why does this happen? (step by step)
- The first render creates a NotesEditor fiber. useState stores draft = notes of customer A.
- The agent picks customer B. SupportPage renders again. At the same place there is again a NotesEditor element.
- Reconciliation: same type, same place, no key, so React updates the props of the existing fiber. The state is kept.
- useState ignores its initial value on later renders, so draft is still A’s notes, while the heading shows B.
- On Save, onSave uses selected.id, which is B. So A’s text is saved on B.
The fix:
<NotesEditor
key={selected.id}
customer={selected}
onSave={n => saveNotes(selected.id, n)}
/>
- When the key changes, React unmounts the old editor (with its state and effects) and mounts a new one. useState runs its initial value again.
- This is the official way to reset all the state of a subtree when “what it shows” changes.
- Do not “fix” it with an effect like
useEffect(() => setDraft(customer.notes), [customer]). It renders once with the wrong text, then again, and it also throws away the agent’s typing on any parent re-render that creates a new customer object.
Follow-up question: The product wants to keep an unsaved draft for each customer when the agent switches back and forth. What changes?
Follow-up answer:
- A reset with key now throws the draft away, so the draft must live outside the editor.
- Lift the drafts up into the parent (or a small store), as a map from customer id to text, and pass the right draft down with an onChange.
- Show a “not saved” mark, and maybe save drafts to localStorage so a reload does not lose them.
Red flag: Thinks React matches components by their props or by the customer object, or fixes it with an effect that copies props into state.
Show answer
Not saved in this browser.