Questions 101–120 of 150 · 0 of 20 on this page marked learned
101.react-0101Easyfresher
Is the virtual DOM faster than the real DOM? Explain the common myths about it.
No. The virtual DOM is not faster than well-written direct DOM updates, because it adds work on top of them: React builds a tree of plain objects, compares it with the previous one and then updates the real DOM. Its value is that you describe the UI as a function of state and React finds a reasonably small set of DOM changes for you. It is a productivity and predictability tool, and the cost is acceptable, not zero.
Full answer
The phrase "the virtual DOM makes React fast" is repeated so often that it has become a myth. The accurate statement is narrower.
What a virtual DOM is. When a component renders, it returns React elements, which are plain JavaScript objects such as { type: 'p', props: { className: 'note' } }. They are cheap to create. React compares the new tree with the previous one (reconciliation) and applies only the differences to the real DOM.
Myth 1: it is faster than the DOM. Any change React makes to the DOM could be written by hand with equal or better speed, because React does the same DOM operations plus the cost of creating and comparing objects. The real comparison is with the alternative of re-creating all DOM nodes on every change, which would be slow and would lose focus, scroll position and input state.
Myth 2: React never touches unchanged DOM. This is mostly true for text and attributes, but React still re-runs component functions and compares trees even when nothing changed. That work is what memo, state colocation and the React Compiler reduce.
Myth 3: the virtual DOM is why React exists. React's core idea is declarative UI: you write what the screen should look like for the current state, and React figures out how to get there. The virtual DOM is one implementation technique. Other libraries reach the same goal differently: Svelte compiles updates at build time, and Solid and Vue's reactivity system track which exact values changed, so they skip the tree comparison.
Myth 4: the virtual DOM is a copy of the browser DOM. It is not. It is a lightweight description with no layout, no event system and no methods. React's internal Fiber tree, which also stores state and effects, is separate from the elements.
Where React is slow in practice is rarely the DOM write. It is rendering too many components, expensive work inside render, and large lists. Profile before optimizing.
A good interview answer: the virtual DOM is a trade-off that gives a simple programming model with good-enough performance, and React keeps adding tools (batching, transitions, compiler) to reduce the cost.
The example shows that an element is a plain object, and that a state change touches one text node.
This ran as a script. A React element is a plain object. After a click the component function ran again, but the real DOM received one text change, and the "Static text" paragraph was not touched. Output of the run:
element type: p, className: note, plain object: true
DOM mutations after one click: ["characterData"]
button text now: Clicked 1
Key points
The virtual DOM adds work, so it is not faster than careful manual DOM updates.
Its benefit is declarative code: describe the UI for the current state and let React compute the changes.
Elements are plain objects, not a copy of the browser DOM.
Other libraries (Svelte, Solid, Vue) avoid tree comparison with compile-time or fine-grained reactivity.
Real slowness usually comes from rendering too much, not from DOM writes. Measure first.
Common mistakes
Saying the virtual DOM is faster than the DOM.
Describing the virtual DOM as a copy of the browser DOM.
Believing React never re-runs work for unchanged parts of the tree.
Optimizing DOM writes while ignoring expensive renders.
Treating the virtual DOM as the main reason to choose React.
Follow-ups
How do Svelte and Solid update the DOM without a virtual DOM?
What is the difference between React elements and the Fiber tree?
What does the React Compiler change about unnecessary renders?
Tips
Open with "no, and here is what it actually gives you". It shows you can challenge a popular claim.
Name an alternative approach, such as compile-time updates in Svelte.
Finish with measuring and the real causes of slowness.
102.react-0102Easyfresher
What does one-way data flow mean in React, and how do children send information back to parents?
Data flows down: a parent passes values to children through props, and children cannot change those props. When a child needs to change something, the parent passes down a function, and the child calls it with the new value. The parent updates its own state, and the new value flows down again. This makes it clear where each piece of data is owned and how it changes.
Full answer
In React, props travel from parent to child only. A child receives them as read-only inputs. It cannot assign to a prop, and it has no direct way to reach up and edit the parent's variables. This is called one-way (unidirectional) data flow, or "data down, actions up".
The cycle has four steps. State lives in one owner component. The owner passes values down as props. A child reports an event by calling a callback prop, for example onSelect(id). The owner handles it by updating its state, which re-renders it and gives every child fresh props.
Why it is useful. When something on screen is wrong, you can trace it upward: which component owns this value, and which handler changes it. There is one place to look. Two-way binding systems (as in older AngularJS) let a change in a child update the parent's data directly, which can create loops and makes updates harder to follow. React's controlled inputs are the same cycle: the value comes down, the onChange goes up.
What is not one-way. Context lets a provider send values to any descendant without passing props through each level, but the flow is still downward. Refs and external stores can break the pattern, because they are mutable and read outside of render, so use them deliberately.
Common design question: where should state live? Put it in the closest component that is above everything that needs it (lifting state up).
The example has a parent that owns the selected course and a child list that reports clicks.
The parent owns selectedId and passes down both the value and the setter as onSelect. The check pressed both buttons in order, so the final state is the second course. Rendered result: <div><ul><li><button aria-pressed="false">Maths</button></li><li><button aria-pressed="true">Science</button></li></ul><p>Selected: Science</p></div>
Key points
Props flow from parent to child and are read-only.
Children communicate upward by calling callback props.
The owner component updates its state and the new values flow down again.
One owner per piece of state makes bugs easy to trace.
Controlled inputs, and context, follow the same downward flow.
Common mistakes
Trying to assign to a prop inside the child.
Copying a prop into state and getting out of sync with the parent.
Mutating an object received through props.
Duplicating the same state in parent and child.
Describing controlled inputs as two-way binding.
Follow-ups
How does one-way data flow help when debugging?
How does context fit into one-way data flow?
How do Redux or Zustand keep the flow predictable?
Tips
Use the phrase "data down, actions up".
Link it to controlled inputs. It shows you see the same pattern.
Mention where state should live when two siblings need it.
103.react-0103Easyfresher
Why does React warn "A component is changing an uncontrolled input to be controlled", and why is a file input always uncontrolled?
React decides whether an input is controlled by checking whether the value prop is undefined on the first render. If it starts undefined (uncontrolled) and later becomes a string (controlled), React warns because the two modes behave differently. The fix is to give the state an initial empty string or use value={x ?? ''}. A file input is always uncontrolled because its value can only be set by the user, so you read it with an event or a ref.
Full answer
A controlled input gets its value from React state through the value prop and reports changes with onChange. An uncontrolled input keeps its own value in the DOM, and you read it when needed. React picks the mode by looking at value: if it is not undefined, the input is controlled.
The warning appears when this changes during the lifetime of the input. A typical cause is const [name, setName] = useState() with <input value={name} />. On the first render the value is undefined, so the input is uncontrolled. After the user types, state becomes a string, so React switches modes. The reverse switch (controlled to uncontrolled) happens when state becomes undefined or null, for example after resetting with setName(undefined) or reading a field missing from API data.
Why it matters. In controlled mode, React owns the value and resets the DOM to match state after every render. In uncontrolled mode the DOM owns it. Switching in the middle can lose text or leave the DOM and state different. React warns so you pick one mode.
Fixes. Initialize state with an empty string: useState(''). When the value may come from data that can be missing, normalize it: value={user.name ?? ''}. For checkboxes use checked with a boolean, and pass onChange whenever you pass value, or React warns about a read-only field.
File inputs. <input type="file" /> cannot be controlled, because browsers do not allow code to set the selected file for security reasons (only the user can choose). You read the files from the change event (event.target.files) or from a ref, and keep what you need (the File objects) in state. You may reset it by changing the key or by resetting the form.
When to use uncontrolled on purpose: simple forms read on submit through FormData, or inputs managed by a form library.
The example shows a safe controlled field and a file input read from the change event.
The user prop is missing here, so user.name is undefined and the nullish default keeps the input controlled from the first render. The check typed a name. The warning itself appears in the browser console when the default is left out. Rendered result: <form><label>Name<input value="Asha"></label><label>Photo<input type="file"></label><p>Hello Asha, file: no file chosen</p></form>
Key points
Controlled means value is not undefined. Starting undefined and becoming a string triggers the warning.
Initialize with an empty string or normalize missing data with ?? ''.
Passing value without onChange creates a read-only field and a warning.
A file input is always uncontrolled because code cannot set the selected file.
Read file inputs through onChange or a ref, and store the File objects you need.
Common mistakes
Calling useState() with no initial value for a controlled input.
Passing null from an API directly to value.
Passing value without onChange.
Trying to set the value of a file input from state.
Switching between value and defaultValue on the same input.
Follow-ups
What is the difference between defaultValue and value?
How would you clear a file input after upload?
When is an uncontrolled form with FormData the better choice?
Tips
Explain how React decides the mode (value is undefined or not).
Give the nullish fallback fix. It is a one-line answer.
Mention the browser security reason for file inputs.
104.react-0104Easyfresher
When should you use a ref instead of state, and what happens to the screen when each one changes?
Use state for anything that appears on screen, because changing state re-renders the component. Use a ref for values that must survive re-renders but do not affect what is rendered, such as timer ids, DOM nodes, or the previous value. Changing ref.current does not cause a re-render, and it should not be read or written during render. If changing a value should update the screen, it belongs in state.
Full answer
Both state and refs persist across re-renders, which is why they are easy to confuse. The difference is what a change does.
State. setCount(1) tells React that the output may have changed, so React re-renders the component with the new value. State is treated as a snapshot for each render, and must be updated through the setter. Use it for anything the user sees or any value that decides what is rendered.
Refs. useRef(0) returns an object { current: 0 } that is the same object on every render. Assigning ref.current = 5 changes the object but does not notify React, so nothing re-renders. Good uses:
Holding a DOM node: <input ref={inputRef} /> and then inputRef.current.focus().
Storing an id that must be cleared later (setTimeout, setInterval, subscriptions).
Remembering a value between renders without displaying it (previous props, a render counter for debugging, a mutable flag such as "is mounted").
Rules. Do not read or write ref.current during rendering, except for the one-time lazy initialization, because render must stay pure and React cannot track the change. Read and write refs in event handlers and effects. If you catch yourself showing a ref value in JSX, you probably want state.
A useful test: "If this value changes, must the screen change?" Yes means state. No means a ref may be right. Another point: a ref update is immediate and synchronous, while a state update is applied on the next render, which makes a ref handy inside callbacks that need the latest value. Be careful, because it also avoids React's change tracking, so bugs are harder to find.
The example changes a ref and then state and logs what each render sees.
The log reads the ref during render only to show the effect for teaching. Real components should not do that. The first click changed the ref and caused no render. The second click changed state, and the new render then saw both values. Output of the run:
render: state=0, ref=0
render: state=1, ref=1
Key points
State changes cause re-renders. Ref changes do not.
Use state for what is displayed. Use refs for DOM nodes, timer ids and non-visual values.
Do not read or write ref.current while rendering.
If a ref value shows up in JSX, it probably should be state.
Refs update immediately. State updates apply on the next render.
Common mistakes
Storing displayed values in a ref and wondering why the screen does not update.
Reading or writing ref.current during rendering.
Using state for timer ids and causing extra renders.
Using a ref to avoid fixing a stale closure that should be solved with proper dependencies.
Mutating state objects instead of using the setter.
Follow-ups
How do you keep the previous value of a prop with a ref?
Why can a ref be safer than state inside a timer callback, and what is the risk?
Can a ref hold a DOM node and a value at the same time?
Tips
Give the screen test: "must the screen change?".
Name three non-visual uses of refs.
Mention the render-purity rule.
105.react-0105Easyfresher
What causes a React component to re-render, and what does not?
A component re-renders when its own state changes, when its parent re-renders (even with the same props, unless memoized), or when a context it reads changes. It does not re-render when you mutate a ref, assign to a plain variable, or set state to the same value (React bails out). Re-rendering means React calls the function again. It does not always mean the DOM changes.
Full answer
A render is a call to your component function to compute what the UI should look like. React then compares the result with the previous one and updates the DOM only where it differs. So "re-render" and "DOM update" are different things.
Triggers:
State change. Calling a state setter with a new value schedules a render of that component.
Parent render. When a component renders, React renders its children too, with new props objects, even if the values are equal. This is the most common cause of extra renders. React.memo can skip a child when its props are shallowly equal.
Context change. Every component that reads a context with useContext re-renders when the provider's value changes by reference, even if its parent did not render.
Hook subscriptions, such as useSyncExternalStore or a store selector, when their data changes.
Not triggers:
Mutating a ref (ref.current = 1) or a normal variable. React does not know about it.
Setting state to the same value (compared with Object.is). React bails out, although it may call the component one more time before stopping in some cases, without updating children.
Mutating state objects directly (user.name = 'x'). The reference did not change, so React may not notice.
Props changes alone never cause a render, because props only change when the parent renders.
Why this matters. Slow screens usually come from too many unnecessary renders of expensive components. The first tools are to move state down, split components, and then use memo, useMemo and the Compiler. Do not try to block all renders. Renders are cheap when components are light.
The example logs which components render for each type of change.
The check pressed the four buttons in order: change ref, set the same value, set a new value, and change the theme. The first two presses printed nothing, so no render happened. Set new value rendered App and Plain, but not Memoized. ThemeReader rendered each time only because its parent did, so this example does not isolate a context-only render. Output of the run:
App rendered
Plain child rendered
Memoized child rendered
ThemeReader rendered with light
App rendered
Plain child rendered
ThemeReader rendered with light
App rendered
Plain child rendered
ThemeReader rendered with dark
Key points
State changes, parent renders and context changes trigger renders.
A render is a function call. The DOM only changes where output differs.
Children re-render with their parent unless memoized.
Ref mutations, variable assignment and same-value state do not trigger renders.
Fix slowness by moving state down before memoizing.
Common mistakes
Assuming a child only re-renders when its own props change.
Thinking a re-render always updates the DOM.
Mutating state and expecting a re-render.
Wrapping everything in memo before measuring.
Forgetting that a context change re-renders all readers.
Follow-ups
How does React.memo compare props?
How can you prevent context readers from re-rendering on every change?
What does it mean that React "bails out" of a state update?
Tips
Separate "render" from "DOM update". Interviewers listen for it.
List the three triggers and the common non-triggers.
Suggest moving state down as the first fix.
106.react-0106Easyfresher
What does this component log when the button is clicked, and why does console.log show the old state right after setState?
It logs the old value. State is a snapshot for each render: the handler runs with the count from the render that created it, and setCount schedules the next render but does not change the variable. The next render gets the new value. To use the new value immediately, compute it in a local variable, or read it in the next render or in an effect.
Full answer
A common beginner puzzle: after setCount(count + 1), console.log(count) prints the previous number. The reason is how state works.
Each render calls your component function once and gives it constant values: count is 0 for that call, like a local const. An event handler created in that render closes over that count. Calling setCount(1) does not mutate the variable. It asks React to render again later. The next call of the component receives count = 1, and the handlers created there see 1.
So inside the same handler, every read of count returns the same value, even after several setter calls, and even inside setTimeout created in that handler. This is why setCount(count + 1) called three times adds only one, and the functional form setCount((c) => c + 1) is used when each update depends on the previous.
How to get what you need:
If you need the new value now, compute it: const next = count + 1; setCount(next); console.log(next);.
To react to a state change, use the next render: put the code in the component body (derived values), or in an effect with the state in its dependencies.
For updates that depend on the previous state, use the updater function.
Related: React batches updates in a handler, so there is a single re-render after the handler finishes, not one per setter call.
The example logs inside the handler, in the render, and after a timer.
jsx
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
console.log('render with count = ' + count);
function handleClick() {
setCount(count + 1);
console.log('right after setCount(count + 1): ' + count);
setCount(count + 1);
setTimeout(() => console.log('in a timer started by the same click: ' + count), 0);
const next = count + 1;
console.log('local variable next: ' + next);
}
return <button onClick={handleClick}>Count: {count}</button>;
}
The check clicked once. The click called setCount twice with the same snapshot value, so the count went from 0 to 1, not 2. Output of the run:
render with count = 0
right after setCount(count + 1): 0
local variable next: 1
render with count = 1
in a timer started by the same click: 0
Key points
State is a snapshot, constant for the whole render and for handlers created in it.
The setter schedules a re-render. It does not change the current variable.
Compute the next value in a local variable if you need it immediately.
Use updater functions when the new state depends on the previous state.
Updates in one handler are batched into one render.
Common mistakes
Expecting the variable to change right after calling the setter.
Calling setCount(count + 1) several times and expecting several increments.
Reading state in a timer and expecting the newest value.
Using an effect just to read the new value of a variable you can compute.
Mutating state to make the new value appear immediately.
Follow-ups
How does the updater form change the result?
Why does React batch these updates into one render?
How would you read the latest value inside a timer callback?
Tips
Say "snapshot" and compare it to a const in each render.
Give the local variable fix, then the updater fix.
Mention that the timer also sees the old value.
107.react-0107Easyfresher
Which components re-render when state changes inside one component, and why does passing children as a prop prevent a re-render?
When a component's state changes, React re-renders that component and every child element it creates in its own render. Elements passed in as children were created by the parent earlier, so they keep the same identity and React reuses the previous result without calling those children again. A component that creates its children itself re-renders them each time. This is why moving state into a small wrapper component limits re-renders.
Full answer
React compares elements by identity before rendering them. When a component function runs, it produces new element objects for the children it writes in JSX, and React must render those children again. If an element object is exactly the same object as in the previous render, React skips it, because the element and its props did not change.
Consider two ways to write a counter. In the first, the counter component writes <Plain /> inside its own JSX. Every state change runs the counter function, which creates a new <Plain /> element, so Plain re-renders. In the second, the counter receives children as a prop, and the parent that created <Static /> does not re-render when the counter's own state changes. The children prop keeps the same element object, so Static is skipped.
This gives a free optimization: if only part of a component depends on frequently changing state, move that state and the parts using it into a new component, and pass the rest as children or props. No memo is required.
Remember the limits. If the parent of the counter re-renders, it creates a new <Static /> element, and Static re-renders too unless it is memoized. Passing an inline object or function as a prop makes memo fail for the same identity reason.
Puzzle tip: to predict renders, ask who owns the state, and then ask which elements were created in the render that is running.
The example has both patterns and logs the renders.
The check pressed each button once. After the first button only the counter renders, and after the second button the counter and Plain render. Output of the run:
CounterWithChildren rendered
Static rendered
CounterWithOwnChild rendered
Plain rendered
CounterWithChildren rendered
CounterWithOwnChild rendered
Plain rendered
Key points
A state change re-renders the component and the elements it creates during that render.
Elements received as children keep their identity and are skipped.
Moving state into a wrapper limits re-renders without memo.
A parent re-render creates new elements, so children re-render again unless memoized.
To predict renders, find the state owner and who created each element.
Common mistakes
Assuming a child re-renders only when its props change.
Adding memo when moving state down would be simpler.
Forgetting that a parent re-render creates new child elements.
Passing inline objects and functions to memoized children.
Lifting state higher than needed.
Follow-ups
What changes if App itself re-renders?
How does React.memo decide to skip a render?
How does the React Compiler relate to this identity trick?
Tips
Explain element identity in one sentence.
Offer "move state down" as the first optimization.
Predict the log before running it. Interviewers like that.
108.react-0108Easyfresher
How does React compare with Angular and Vue, and how would you choose between them?
React is a UI library focused on rendering with components and JavaScript, so routing, data fetching and forms come from the ecosystem. Angular is a full framework with TypeScript, dependency injection, routing, forms and tooling built in. Vue sits in between: a progressive framework with single-file components, built-in reactivity and official router and store libraries. Choose by team skills, project size, need for conventions and hiring, because all three can build most apps.
Full answer
All three build component-based single-page apps and can render on the server. They differ in scope, style and learning curve.
React. A library for building UI. You write components as functions that return JSX, and state is updated through hooks and re-rendering. It has a small core, so you choose routing (React Router, TanStack Router), data fetching (TanStack Query), state (Redux Toolkit, Zustand) and a framework such as Next.js. The strengths are a large ecosystem, flexibility, a huge job market, React Native for mobile and Server Components. The cost is decision fatigue and inconsistent project structures.
Angular. A complete framework maintained by Google, written in TypeScript. It includes a router, forms, HTTP client, dependency injection, testing tools and a CLI. Templates use HTML with directives, and recent versions use signals for fine-grained reactivity and a new control flow syntax (@if, @for). Strengths are strong conventions that suit large teams and long-lived enterprise apps. The cost is a steeper learning curve and more concepts to learn.
Vue. A progressive framework created by Evan You. Components are single-file components (template, script, style) and reactivity is built in with ref and reactive, so Vue tracks exactly which data a component uses and updates only that. It has official libraries for routing and state (Pinia) and a gentle learning curve. The ecosystem and job market are smaller than React's, although strong in some regions.
Key technical differences: React re-runs component functions and compares output, while Vue and Angular signals track dependencies and update more precisely. React favors JavaScript for logic in templates (JSX), Vue and Angular use template languages.
How to choose: team experience first, then the project (enterprise app with strict structure favors Angular, quick product with flexibility favors React or Vue), the ecosystem needs (mobile with React Native), and hiring.
Be fair in interviews: do not claim one is best. Show that you understand the trade-offs.
The example is the React version of a counter. The Vue and Angular equivalents are shown in the answer text and were not run.
jsx
import { useState } from 'react';
// React: state lives in a hook, and the component function runs again after each change.
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Clicked {count}</button>;
}
Only the React counter was run here. Equivalent counters in Vue 3 (`const count = ref(0)` in a script setup block with `{{ count }}` in the template) and in Angular (`count = signal(0)` with `count.update(c => c + 1)`) are described in prose and not executed. Rendered result: <button>Clicked 1</button>
Key points
React is a UI library. Angular is a full framework. Vue is a progressive framework in between.
React re-renders and compares. Vue and Angular signals track dependencies for precise updates.
React has the largest ecosystem and React Native, but needs more choices.
Angular suits large teams that want strong conventions.
Choose by team skills, project needs and hiring, not by claims that one is best.
Common mistakes
Calling React a framework, or stating that it includes routing.
Declaring one technology the winner without context.
Comparing speed from outdated benchmarks.
Ignoring the team's existing skills when choosing.
Forgetting that frameworks such as Next.js fill React's gaps.
Follow-ups
What does Angular's dependency injection give you that React does not have?
How do signals differ from React state?
What would you pick for a small team building a dashboard, and why?
Tips
Stay neutral and give trade-offs.
Mention the library versus framework difference first.
Say your choice depends on team and project.
109.react-0109Easyfresher
What is the difference between a React component, a React element and a component instance?
A component is a function (or class) that describes a piece of UI. An element is the plain object that describes one use of a component or a DOM tag, produced by JSX, such as <Counter />. An instance is the running copy that React creates and keeps in its tree for an element, holding its own state. Two elements of the same component make two instances with separate state.
Full answer
Three words are often mixed up, and interviewers use them to check whether you understand how React works.
Component. A reusable definition: function Counter() { ... }. It is only a blueprint. Writing it runs nothing.
Element. A lightweight, immutable description of what you want on screen: <Counter label="A" /> creates an object like { type: Counter, props: { label: 'A' } }. Elements are cheap and thrown away on each render. An element can describe a DOM node (type: 'button') or a component (type: Counter). React never changes an element. When something changes, you return a new one.
Instance. When React renders an element for the first time, it creates the thing that lives in its internal tree for that position (a Fiber node with state, refs and effects). For a class component, that is a real object created with new. For a function component, there is no visible object, but React stores hooks state for it in the same way, so it behaves like an instance. State belongs to the instance, not to the component definition. That is why you can render the same component twice and get independent state.
What keeps an instance alive: its type and its position in the tree (and key). If the same component type is rendered at the same position in the next render, React keeps the instance and updates props. If the type or key changes, React unmounts it, which destroys its state, and creates a new one.
Why this matters: it explains why state resets when a component moves, why keys matter, and why you cannot call a component as a normal function and keep its state.
The example renders two counters from one component and checks that their state is independent.
jsx
import { useState } from 'react';
function Counter({ label }) {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Add to {label}</button>
<p>
{label}: {count}
</p>
</div>
);
}
const element = <Counter label="X" />;
console.log('component is a function: ' + (typeof Counter === 'function'));
console.log('element is an object with type === Counter: ' + (typeof element === 'object' && element.type === Counter));
export default function App() {
return (
<div>
<Counter label="First" />
<Counter label="Second" />
</div>
);
}
Counter is the component, each tag in App creates an element, and React keeps two instances. The check pressed Add to First twice and left the second counter alone. Output of the run:
component is a function: true
element is an object with type === Counter: true
after two clicks on the first counter only: First: 2 | Second: 0
Key points
A component is a definition (function or class). An element is a plain object describing a use of it.
An instance is what React keeps in its tree, with its own state, for an element.
Rendering the same component twice makes two instances with separate state.
React keeps an instance while type, position and key stay the same.
Elements are cheap and immutable. Instances hold state.
Common mistakes
Calling a component function directly instead of rendering an element.
Thinking state is shared between two uses of the same component.
Saying a component is the same as an element.
Changing an element after creating it.
Forgetting that changing a component's type at a position resets its state.
Follow-ups
What happens to state when the same position renders a different component type?
How do keys affect instances?
Why can function components be called "instances" even though there is no object?
Tips
Use the blueprint, description and live copy wording.
Mention type and position as what keeps the instance alive.
Tie it to state resets and keys.
110.react-0110Easyfresher
What is lazy initialization of state in useState, and why does useState(expensive()) run the function on every render?
The argument to useState is only used on the first render, but JavaScript still evaluates the expression every time the component runs. So useState(expensive()) calls expensive() on every render and throws the result away after the first. Passing a function, useState(() => expensive()), makes React call it once, on the first render only. Use it for costly work such as reading localStorage or building large structures.
Full answer
useState(initialValue) stores initialValue the first time the component renders. On later renders React ignores the argument and returns the current state. This often leads to the belief that the argument is only evaluated once. It is not. The argument is an ordinary JavaScript expression, evaluated before useState is called, on every render.
So const [items, setItems] = useState(createItems()) calls createItems() on each render. The result is ignored after the first render, but the cost is paid every time: parsing JSON from localStorage, filtering a big array, or creating a large object. With frequent re-renders this becomes slow, and it can also be a source of surprising side effects.
Lazy initialization fixes it. If you pass a function, useState(() => createItems()), React calls it only during the first render and uses the return value as the initial state. The function must be pure and take no arguments. You can also pass the function directly: useState(createItems).
When to use it:
Reading from localStorage or sessionStorage for an initial value (guarding against server rendering).
Building large data structures or running filters and sorts.
Anything that parses, loops or allocates a lot.
When not needed: simple literals such as 0, '', [] or {} are cheap, although a new empty array each render is harmless here because only the first is used.
Same idea elsewhere: useRef(new Expensive()) also creates a new object on every render. The usual pattern is to create the value lazily when ref.current is null. useReducer supports a third init argument for the same purpose. useMemo is for recomputation caching, not for initial state.
Strict Mode calls initializer functions twice in development, as it does with other render code, to check they are pure.
The check pressed each button once. Each press re-renders its component, and the eager form calls createItems again while the lazy form does not. Output of the run:
eager: createItems call number 1
lazy: createItems call number 2
eager: createItems call number 3
Key points
The useState argument is evaluated on every render, even though React only uses it on the first.
Pass a function (useState(() => expensive())) so React calls it once, on the first render.
The initializer must be pure and take no arguments.
Use it for storage reads, big data and heavy computation. Plain literals do not need it.
useRef and useReducer have similar patterns (lazy creation and the init argument).
Common mistakes
Believing the useState argument is only evaluated once.
Reading localStorage directly in the argument on every render.
Passing a function that has side effects as the initializer.
Using useMemo to set initial state instead of lazy initialization.
Creating objects with new inside useRef(...) on every render.
Follow-ups
How would you read an initial value from localStorage safely with server rendering?
Why does Strict Mode call the initializer twice?
How does the init argument of useReducer work?
Tips
Say "the expression runs every render, React just ignores the result". That sentence is the answer.
Give a concrete example such as localStorage.
Mention that the initializer must be pure.
111.react-0111Easyfresher
Why are props read-only in React, and what happens if you try to change them?
A component must act like a pure function with respect to its props: same props, same output. If a child changed its props, the parent and child could disagree, and updates would be hard to trace. In development React freezes the props object, so assigning to it throws an error in strict mode code. To change data, ask the parent through a callback, or copy the prop into local state only when you need your own editable copy.
Full answer
Props are the inputs a parent gives to a child. The rule in React docs is that all components must act like pure functions with respect to their props. A pure function does not modify its inputs, so a component should never write to props.name or mutate an object or array it received.
Reasons. First, predictability: the parent owns the data. If a child could change it, two components would hold different views of the same value, and the next parent render would overwrite the child's change. Second, React relies on comparing values by reference to skip work (memo, effect dependencies, useMemo). Mutating an object in place leaves its reference unchanged, so React cannot see the change and the UI goes stale. Third, concurrent rendering may render a component multiple times or discard a render, so side effects on shared data lead to bugs.
What happens in practice. In development, React freezes the props object (Object.freeze), so props.title = 'x' throws a TypeError in strict mode code, which includes ES modules and classes. The freeze is shallow: it protects the props object itself, not the objects inside it. A child can still mutate props.user.name without an error, and that is a bug that React cannot catch for you. In production the freeze is not applied, so the mistake can silently work and then fail in confusing ways.
What to do instead:
To change a value owned by the parent, call a function passed as a prop (onRename(newName)).
To keep an editable draft, copy the prop into state once (useState(props.initialName)), name the prop initialName to make the intent clear, and decide how to sync it (key reset).
To transform a value, compute a new one during render without changing the original ([...props.items].sort(...), since sort mutates).
The example shows the frozen object and a safe derived copy.
jsx
import { renderToStaticMarkup } from 'react-dom/server';
function Course(props) {
console.log('props object is frozen: ' + Object.isFrozen(props));
try {
// ES modules run in strict mode, so assigning to a frozen object throws.
props.title = 'Changed';
} catch (error) {
console.log('assigning to props threw: ' + error.constructor.name);
}
const sorted = [...props.lessons].sort();
return (
<p>
{props.title}: {sorted.join(', ')}
</p>
);
}
const lessons = ['State', 'Props', 'Effects'];
console.log(renderToStaticMarkup(<Course title="React" lessons={lessons} />));
console.log('original array unchanged: ' + lessons.join(', '));
The first two lines show the freeze in the development build of React, which is what this script ran. A production build does not freeze the object. The array copy keeps the original order. Output of the run:
props object is frozen: true
assigning to props threw: TypeError
<p>React: Effects, Props, State</p>
original array unchanged: State, Props, Effects
Key points
Components should behave like pure functions of their props and never modify them.
Mutating props breaks the parent's ownership and defeats reference comparisons.
In development React freezes the props object, so assignment throws in strict mode code. The freeze is shallow.
Use callback props to request changes, or copy into state for a local draft.
Copy before sorting or reversing prop arrays, because those methods mutate.
Common mistakes
Assigning to props inside a component.
Calling sort or reverse on an array received as a prop.
Mutating a nested object from props because the freeze is shallow.
Copying a prop into state and expecting it to follow later prop changes.
Relying on the development error as the only protection.
Follow-ups
How would you keep a form draft that starts from a prop value and resets when the prop changes?
Why does the freeze not apply to nested objects?
How do TypeScript readonly types help here?
Tips
Describe components as pure functions of props.
Mention that the freeze is dev-only and shallow.
Give the callback pattern as the correct way to change parent data.
112.react-0112Easyfresher
What is a single-page application, how does React implement client-side navigation, and what are the trade-offs against a multi-page site?
A single-page application loads one HTML page and then updates the content with JavaScript, changing the URL with the History API instead of requesting a new document for each page. Navigation feels instant and keeps state, but the first load is heavier, search engines and link previews see less without server rendering, and you must handle routing, scroll and focus yourself. Multi-page sites request a new HTML page per navigation and are simpler and more reliable for content.
Full answer
In a traditional multi-page application (MPA) each link asks the server for a new HTML document and the browser replaces the whole page. A single-page application (SPA) loads a shell once. When the user clicks a link, JavaScript intercepts the click, changes the URL without a reload and renders the matching component.
How it works in React. React itself has no router. A library such as React Router listens for link clicks, calls history.pushState to change the URL, listens for the back and forward buttons (popstate), and renders the component for the current URL. The example below builds a tiny version with the hashchange event. Real routers use the History API for clean URLs, so the server must return the same index.html for every path, or deep links return a 404.
Benefits of an SPA: fast transitions after the first load, state kept across pages (a playing video, an open sidebar), smooth animations between views and a single codebase for an app-like experience.
Costs: a larger first download (all the framework code), a blank page until JavaScript runs (hurts first paint on slow devices), weaker out-of-the-box search engine optimization and link previews because the initial HTML is empty, extra work for accessibility (focus and announcements after navigation, scroll restoration, page titles), and memory growth in long sessions.
Mitigations: code splitting by route, server-side rendering or static generation (Next.js, Remix and similar frameworks), prerendering key pages and a loading skeleton.
When an MPA is better: mostly content pages (blogs, documentation, marketing). Modern frameworks blur the line by serving HTML for the first request and then taking over as an SPA.
The example is a minimal hash router that changes content without loading a new page.
The check clicked About and then Courses. The content changed and the number of page loads stayed at zero, because only the hash changed. A hash router is the simplest form. Real routers use the History API. Output of the run:
start: Home | url hash | page loads 0
after clicking About: About | url hash #/about | page loads 0
after clicking Courses: Courses | url hash #/courses | page loads 0
Key points
An SPA loads one page and swaps content with JavaScript while changing the URL with the History API.
React needs a router library for URLs, and the server must serve index.html for all paths.
Benefits: fast navigation and preserved state. Costs: heavy first load, SEO and accessibility work.
Mitigate with route code splitting, server rendering or static generation.
Content-heavy sites often fit multi-page or server-rendered approaches better.
Common mistakes
Forgetting that the server must return index.html for every route when using the History API.
Ignoring page titles, focus and scroll position after a client-side navigation.
Using plain anchors with onClick and breaking open-in-new-tab behaviour.
Shipping the whole app in one bundle.
Relying on an SPA for content that needs good search indexing, without server rendering.
Follow-ups
How does React Router change the URL without a reload?
How would server-side rendering change the first load of an SPA?
How do you handle focus for screen readers after a client-side navigation?
Tips
Mention the History API and the index.html fallback.
State both the benefits and the SEO and accessibility costs.
Say modern frameworks combine server rendering with SPA navigation.
113.react-0113Easyfresher
In what order do render, effects and cleanups run for a parent and a child component, including when dependencies change and when components unmount?
Rendering goes parent first, then child. After the commit, effects run child first, then parent, because React finishes children before parents. When dependencies change, the old effect's cleanup runs before the new effect. On unmount, cleanups run for the removed components. Know the sequence by running a logging example, and remember cleanup always sees the values from the render that created the effect.
Full answer
Order puzzles test whether you understand the render and commit phases.
Render phase. React calls components top-down: the parent function first, then the child. This phase should be pure.
Commit phase. React updates the DOM, then runs layout effects, then (after paint, usually) passive effects (useEffect). Effects run in child-to-parent order, like the completion of a tree walk, so the child's effect runs before the parent's effect, even though the parent rendered first.
Updates. When a dependency changes, React renders again and, after commit, first runs the cleanup of the previous effect (with the old values it captured) and then the new effect. Effects whose dependencies did not change are skipped. All cleanups of the changed effects run before any of the new effects of that commit.
Unmount. When a component is removed, its cleanup runs once. React runs the cleanups for the removed subtree, and you should not depend on a particular order between parent and child cleanups. Cleanup should only release what its own effect created.
Strict Mode in development adds an extra setup, cleanup, setup cycle on mount to expose missing cleanup. The example below runs without Strict Mode so the order is clear.
Practical consequences: a parent effect can rely on child effects having run (and child refs being attached), but should not assume order for unmount cleanups. Always write cleanup to undo exactly what the effect did.
The example logs every step for a parent and a child. Press Update to change a dependency, then Remove to unmount.
The mount lines come first, then the lines after Update, then the lines after Remove. Output of the run (no Strict Mode):
render Parent 1
render Child 1
effect Child 1
effect Parent 1
--- press Update
render Parent 2
render Child 2
cleanup Child 1
cleanup Parent 1
effect Child 2
effect Parent 2
--- press Remove
cleanup Parent 2
cleanup Child 2
Key points
Render runs parent then child. Effects run child then parent after commit.
On a dependency change, the old cleanup runs before the new effect, using the old values.
On unmount, cleanups run once. Do not rely on cleanup order between parent and child.
Layout effects run before passive effects, after DOM updates.
Strict Mode adds an extra setup and cleanup cycle on mount in development.
Common mistakes
Assuming the parent effect runs before the child effect.
Expecting the new effect to run before the old cleanup.
Reading new values inside a cleanup function.
Relying on cleanup order between parent and child on unmount.
Missing the extra setup and cleanup cycle that Strict Mode adds in development.
Follow-ups
How do useLayoutEffect callbacks fit into this order?
What changes when the dependency array is empty?
Why does the cleanup see old values?
Tips
Separate render order (parent first) from effect order (child first).
Say the cleanup uses the values from its own render.
Mention Strict Mode so the interviewer sees you know the dev behaviour.
114.react-0114Easyfresher
What does it mean for a React component to be pure, and which things count as side effects in render?
A pure component returns the same output for the same props, state and context, and changes nothing outside itself while rendering. Side effects in render include mutating variables created outside the component, writing to the DOM, sending requests, starting timers, and reading changing values such as Date.now() or Math.random() for output. Put side effects in event handlers or effects. Strict Mode renders twice in development to expose impurity.
Full answer
React may call your component function more than once, in any order, and sometimes throw the result away (Strict Mode, concurrent rendering, Suspense retries). That is only safe if rendering is pure, like a math function: the same inputs always give the same output, and nothing else is changed.
What purity allows: reading props, state and context, creating new local values (objects, arrays), calling pure helpers and returning JSX. Creating values during render is fine, even when they are mutated afterwards, as long as they were created in the same render. Mutating something that existed before the render started is not fine.
Side effects in render (avoid):
Changing a variable declared outside the component (a module-level counter or array).
Mutating props, state or context objects directly.
Writing to the DOM, document.title, localStorage, or logging to analytics.
Starting timers, subscriptions or network requests.
Output that depends on unstable sources: Math.random(), Date.now(), new Date() without being passed in.
Where effects belong. User-caused changes go in event handlers. Changes needed because the component appeared on screen or because a value changed go in useEffect, which runs after rendering. Synchronization with the DOM before paint uses useLayoutEffect.
Detection. Strict Mode calls component functions twice in development and compares the result expectations. An impure component shows visible bugs, such as a counter that jumps by two. Linting also helps (eslint-plugin-react-hooks and the React Compiler lint rules).
Why it matters beyond correctness. Purity lets React skip renders, reuse results, render in the background and enable the Compiler to memoize safely.
The example renders a component that uses an outer counter and another that gets the value as a prop, in Strict Mode.
jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
let guestCount = 0;
function ImpureGuest() {
guestCount += 1;
return <li>Impure guest #{guestCount}</li>;
}
function PureGuest({ number }) {
return <li>Pure guest #{number}</li>;
}
const container = document.getElementById('root');
createRoot(container).render(
<StrictMode>
<ul>
<ImpureGuest />
<ImpureGuest />
<PureGuest number={1} />
<PureGuest number={2} />
</ul>
</StrictMode>
);
await new Promise((resolve) => setTimeout(resolve, 30));
console.log(container.textContent);
The script rendered the tree inside Strict Mode. The impure component changes an outer variable, so each call counts and the numbers skip. The pure one always shows what it was given. Output of the run:
Impure guest #2Impure guest #4Pure guest #1Pure guest #2
Key points
Pure components give the same output for the same inputs and change nothing outside themselves.
Creating and mutating new local values during render is fine. Mutating pre-existing values is not.
Side effects belong in event handlers or effects, not in render.
Unstable inputs such as Date.now and Math.random make render impure.
Strict Mode double rendering and linting help detect impurity.
Common mistakes
Changing module-level variables during render.
Using Math.random or Date.now directly in the returned JSX.
Fetching data or setting timers in the component body.
Mutating props or state objects.
Disabling Strict Mode to hide the symptoms.
Follow-ups
Why is mutating an object created in the same render acceptable?
Where would you put the work that updates document.title?
How does the React Compiler depend on purity?
Tips
Describe components as math functions.
Say that mutating new local values is fine and give the distinction.
Point to Strict Mode as the detector.
115.react-0115Easyfresher
How do you start a new React project today, and why is Create React App no longer the answer?
Create React App was deprecated by the React team in 2025 and is not maintained for new projects. The React docs recommend starting with a framework (Next.js, React Router in framework mode, or Expo for native) when you need routing, data loading and server rendering. For a client-only app or learning, use a build tool such as Vite (npm create vite@latest). Choose a framework for production sites with SEO needs, and Vite for dashboards, tools and prototypes.
Full answer
Create React App (CRA) bundled Webpack, Babel and a dev server behind one command. It stopped receiving updates, its tooling became slow and outdated, and it never solved routing, data fetching or server rendering. The React team announced its deprecation in early 2025 and updated the docs to point new projects at frameworks or build tools.
Options now:
A framework. Next.js (App Router, Server Components), React Router in framework mode (formerly Remix) and similar choices bring routing, data loading, code splitting, server rendering and deployment support. Choose one when you need SEO, fast first loads, or full-stack features. Expo is the recommended starting point for React Native.
A build tool such as Vite. npm create vite@latest my-app -- --template react creates a small project with a dev server that uses native ES modules and fast hot reloading, and a production build with Rollup or, in recent Vite versions, Rolldown. You add a router and data library yourself. It suits single-page apps, internal tools and learning.
Other tools such as Parcel or Rsbuild exist for specific preferences.
Typical Vite project files: index.html at the root with a <div id="root">, src/main.jsx that creates the root and renders <App /> (inside StrictMode), vite.config.js for plugins (the React plugin), and package.json scripts: dev, build, preview.
How to decide: Will pages need to be indexed by search engines or load instantly? Pick a framework. Is it a logged-in application behind authentication? Vite with a client router is fine. Is the team experienced with a framework? Use it for consistency.
In an interview, say that React is a library, so the "starting point" is a decision about tooling and rendering strategy, and that you can justify the choice.
The example is the entry file that a Vite template creates, run against a root element.
jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
function App() {
return <h1>Hello from a new React app</h1>;
}
// src/main.jsx in a Vite project looks like this. index.html provides <div id="root"></div>.
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);
await new Promise((resolve) => setTimeout(resolve, 30));
console.log('root contains: ' + document.getElementById('root').innerHTML);
This is the entry file of a Vite React template, run against a root element on the box. The build tool, dev server and framework options were not run here. Output of the run:
root contains: <h1>Hello from a new React app</h1>
Key points
Create React App is deprecated and unmaintained for new projects.
Use a framework (Next.js, React Router framework mode) for routing, data and server rendering. Use Expo for native.
Use Vite for client-side apps, tools and learning.
A Vite project has index.html, src/main.jsx, vite.config.js and dev, build and preview scripts.
Choose by SEO needs, first-load performance and team experience.
Common mistakes
Starting a new project with Create React App from an old tutorial.
Choosing a client-only setup for a content site that needs search indexing.
Choosing a framework for a small internal tool and adding unneeded complexity.
Forgetting that the server needs an index.html fallback for client-side routes.
Treating the tool choice as permanent without a migration plan.
Follow-ups
What does a framework give you that Vite does not?
How would you migrate an existing CRA app to Vite?
Where do environment variables go in a Vite project?
Tips
Say CRA is deprecated and name the two modern routes.
Tie the choice to SEO and rendering needs.
Know the files in a Vite project.
116.react-0116Easyfresher
How does a production build of a React app differ from the development build, and why must you ship the production one?
The development build includes extra checks and helpful warnings (invalid hooks, missing keys, hydration diffs, double rendering in Strict Mode) and is larger and slower. The production build removes those checks, minifies the code and enables optimizations. The bundler picks the build from process.env.NODE_ENV, which is replaced at build time. Always measure performance and ship from a production build.
Full answer
React ships one package with two flavours of code, chosen at build time by the value of process.env.NODE_ENV. Bundlers replace that expression with a literal ("development" or "production") and then remove the branches that cannot run (dead code elimination).
Development build. It contains validation and warnings: unique key warnings, invalid hook calls, wrong prop usage, hydration mismatch diffs, DevTools hooks, extra runtime checks, and Strict Mode's double invocation. These make debugging easier but add size and slow down rendering, sometimes by a large factor. Profiling in development gives misleading numbers.
Production build. The checks and error message strings are removed (React keeps short error codes that link to a decoder page), identifiers are minified, and code is smaller and faster. DevTools profiling is limited unless you use a special profiling build.
Consequences:
Always test performance, bundle size and Lighthouse scores against the production build (vite build then vite preview, or next build then next start).
Never deploy the dev server. It serves unbundled modules and is not hardened.
Code that behaves differently in production is usually relying on dev-only behaviour (double rendering, warnings, error overlays).
Your own code can branch on the mode, for example to enable debug tools in development only. The bundler removes the dead branch.
If the replacement is missing and process is undefined in the browser, bundles fail at runtime, so make sure the build defines it (Vite does this for you with import.meta.env.MODE).
Other build outputs worth knowing: source maps (upload to error monitoring, avoid exposing them if source is private), content hashes in file names for caching, and separate chunks for code splitting.
The example uses esbuild to bundle React for both modes and compares them.
jsx
import { build } from 'esbuild';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
const dir = await mkdtemp(path.join(tmpdir(), 'modes-'));
await writeFile(
path.join(dir, 'entry.jsx'),
"import { createRoot } from 'react-dom/client';\ncreateRoot(document.body).render(<h1>Hello</h1>);\n"
);
async function size(mode) {
const result = await build({
entryPoints: [path.join(dir, 'entry.jsx')],
bundle: true,
minify: true,
jsx: 'automatic',
write: false,
nodePaths: [path.resolve('node_modules')],
define: { 'process.env.NODE_ENV': JSON.stringify(mode) },
outfile: path.join(dir, mode + '.js'),
});
return result.outputFiles[0].contents.length;
}
const development = await size('development');
const production = await size('production');
console.log('development bundle is larger than production: ' + (development > production));
console.log('production is smaller by more than 25 percent: ' + (production < development * 0.75));
This ran esbuild on the box for both modes with a tiny entry file that imports react-dom. The comparison is about relative size and does not give exact numbers, which depend on versions. Output of the run:
development bundle is larger than production: true
production is smaller by more than 25 percent: true
Key points
Bundlers choose the React build from NODE_ENV and remove dead branches.
The development build adds warnings and checks and is larger and slower.
Production strips checks, minifies and uses error codes instead of messages.
Measure and ship only the production build. Never deploy the dev server.
Use source maps and hashed file names for debugging and caching.
Common mistakes
Measuring performance in development mode.
Deploying the development server.
Forgetting to define process.env.NODE_ENV for a custom bundler setup.
Publishing source maps of private source code publicly.
Relying on development-only behaviour such as double rendering.
Follow-ups
What is the profiling build of React and when would you use it?
How do bundlers remove dead code?
How do you read production error codes from React?
Tips
Mention NODE_ENV and dead code elimination.
Say you profile only production builds.
Name two things the dev build adds.
117.react-0117Easyfresher
What does React render for 0, an empty string, false, null, undefined, true, NaN, an empty array and an object inside JSX?
React renders strings, numbers (including 0 and NaN) and bigint values as text, and renders arrays by rendering each item. It renders nothing for null, undefined, true and false. An empty string renders an empty text node (nothing visible). Plain objects throw an error. The classic bug is {count && <List />}: when count is 0, React renders the text 0, so compare explicitly (count > 0).
Full answer
JSX expressions inside braces can hold any JavaScript value, and React decides what to draw for each type.
Renders nothing: null, undefined, true, false. This is why {condition && <Banner />} and {condition ? <A /> : null} work. The booleans exist to support the conditional pattern.
Renders text: strings and numbers. This includes 0, negative numbers and NaN. An empty string renders an empty text node, so nothing visible appears. BigInt values render as numbers too.
Arrays are rendered item by item. An empty array renders nothing, and nested arrays are flattened. Items in arrays need keys because React tracks them by position and key.
Objects (other than React elements) are invalid. { {} } or {user} throws "Objects are not valid as a React child". Convert them first, for example JSON.stringify(user) or render a field.
Functions are not valid as children either and produce a warning, because it usually means you forgot to call them.
The famous trap is the && operator with numbers. {items.length && <List />} evaluates to 0 when the array is empty, and React renders the text "0" on screen. Use a boolean condition: {items.length > 0 && <List />}, or the ternary form. The same applies to NaN. Strings behave similarly: {name && <p>{name}</p>} renders nothing for an empty string (an empty text), which is fine visually.
Remember that false is also what && returns for a false boolean, so it renders nothing, and that attributes behave differently from children: aria-hidden={false} renders aria-hidden="false", and disabled={false} removes the attribute.
The example renders each value on its own and prints the HTML.
This ran as a script with renderToStaticMarkup. Each value is wrapped in a paragraph so the result is visible. NaN was left out of the loop because React logs a development warning when it renders it. A separate run confirmed that NaN renders as the text NaN and triggers that warning. Output of the run:
0 -> "<p>0</p>"
empty string -> "<p></p>"
false -> "<p></p>"
true -> "<p></p>"
null -> "<p></p>"
undefined -> "<p></p>"
empty array -> "<p></p>"
array [1, 2] -> "<p>12</p>"
bigint 5n -> "<p>5</p>"
items.length && ... -> "<p>0</p>"
items.length > 0 && ... -> "<p></p>"
plain object -> error: Objects are not valid as a React child (found: object with keys {name})
Key points
null, undefined, true and false render nothing.
Strings and numbers render as text, including 0 and NaN. BigInt renders as text.
Arrays render item by item, and empty arrays render nothing.
Plain objects throw "Objects are not valid as a React child".
Use count > 0 instead of count && ... to avoid rendering a stray 0.
Common mistakes
Writing {items.length && <List />} and rendering 0.
Rendering an object directly in JSX.
Expecting false to print the word false.
Forgetting that attributes handle false differently from children.
Using index-based keys for arrays that change.
Follow-ups
Why does React treat booleans as "render nothing"?
How do you render a Date or an object safely?
How does disabled={false} differ from aria-hidden={false}?
Tips
Lead with the 0 trap. It is the part interviewers ask about.
Give the corrected expression with > 0.
Mention that objects throw while arrays render.
118.react-0118Mediummid
How does React's event system work, what changed in React 17 about event delegation, and how do native and React handlers interact?
React wraps native events in a SyntheticEvent that behaves the same in all browsers, and it uses event delegation: instead of attaching a listener to each element, it attaches one listener per event type to the root container. Before React 17 the listeners were on document. Since React 17 they are on the root container, which makes it safe to run several React versions on one page. A native listener on the target fires first, then React handlers, then listeners on elements above the root.
Full answer
When you write onClick={handleClick}, React does not call addEventListener on that button. At startup, createRoot(container) registers a listener for each supported event type on the root container. When an event bubbles up to the root, React finds the component whose element was the target, then runs the matching handlers of that component and its ancestors, in capture and bubble order, building the path from its own tree.
SyntheticEvent. The object passed to your handler wraps the native event with the same interface across browsers: target, currentTarget, preventDefault(), stopPropagation(), and the original event in event.nativeEvent. Since React 17 it is no longer pooled, so you can read it after an await. A few events behave differently from native ones: React's onChange for inputs fires on every keystroke (like native input), onFocus and onBlur bubble (like focusin and focusout), and onScroll does not bubble.
Event delegation. One listener per type on the root is cheaper than a listener per element, and it works for elements added later. React 16 attached them to document. That caused problems when multiple React versions or other libraries shared a page, because stopPropagation in one world affected another. React 17 moved listeners to the root container, so apps can be embedded in each other and migrate gradually.
Interaction with native listeners. The order for a click on a button inside the root is: native listeners on the button, then React's handlers (when the event reaches the root), then native listeners on ancestors above the root such as document or body. Calling event.stopPropagation() in a React handler also stops the native event at the root, so a document listener will not run. A native listener on document can no longer stop React handlers, because React already ran. Portals send React events through the React tree, not the DOM tree, so a click in a portal bubbles to React ancestors of the portal.
Practical rules: avoid mixing native and React listeners on the same elements; if you attach native listeners in effects, clean them up; prefer onClickCapture when you need capture order.
The example logs the order of native and React handlers.
jsx
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root');
const log = (message) => console.log(message);
function App() {
return (
<div onClick={() => log('React: onClick on the div (parent)')}>
<button onClick={() => log('React: onClick on the plain button')}>Plain</button>
<button
onClick={(event) => {
log('React: onClick on the stopping button');
event.stopPropagation();
}}
>
Stopping
</button>
</div>
);
}
createRoot(container).render(<App />);
await new Promise((resolve) => setTimeout(resolve, 30));
const [plain, stopping] = container.querySelectorAll('button');
plain.addEventListener('click', () => log('native: listener on the button'));
document.addEventListener('click', () => log('native: listener on document'));
log('--- click the plain button');
plain.click();
log('--- click the stopping button');
stopping.click();
This ran as a script in jsdom. The native listener on the button runs first, then the React handlers (the button, then its parent div), then the native listener on document. After stopPropagation in the React handler, the document listener does not run. Output of the run:
--- click the plain button
native: listener on the button
React: onClick on the plain button
React: onClick on the div (parent)
native: listener on document
--- click the stopping button
React: onClick on the stopping button
Key points
React delegates events: one listener per event type on the root container.
React 17 moved listeners from document to the root container, allowing several React versions on one page.
SyntheticEvent wraps the native event, is no longer pooled, and exposes nativeEvent.
Order: native on the target, then React handlers, then native listeners above the root.
stopPropagation in a React handler also stops listeners above the root, such as document.
Common mistakes
Expecting a document listener to run before React handlers.
Using stopPropagation in React and wondering why document-level listeners stop firing.
Reading the event object after an await in React 16 code, where events were pooled.
Adding native listeners in effects without cleaning them up.
Assuming onScroll bubbles.
Follow-ups
Why did React 17 move listeners from document to the root container?
How do React events behave through a portal?
What does the capture variant of an event handler (onClickCapture) change?
Tips
Describe the root-container delegation and the version 17 reason.
Give the order: native target, React, native ancestors.
Mention portals send events through the React tree.
119.react-0119Mediummid
When should logic go in an event handler instead of useEffect, and what are the common "you might not need an effect" cases?
Effects are for synchronizing with things outside React that must happen because the component is on screen. If the logic is a response to something the user did, put it in the event handler. If a value can be calculated from props and state, calculate it during render. Effects that only update state from other state cause extra renders and bugs. Keep effects for subscriptions, timers, network synchronization and similar external work.
Full answer
The React docs have a whole page on this, and interviewers like to ask for examples. The rule of thumb: an effect describes what to synchronize with the outside world, while an event handler describes what to do when the user does something.
Cases where an effect is not needed:
Derived data. useEffect(() => setFullName(first + ' ' + last), [first, last]) renders twice per change, first with a stale value. Compute const fullName = first + ' ' + last during render, and use useMemo only if the calculation is expensive.
Resetting state when a prop changes. Instead of an effect that calls setComment('') on userId change, give the component a key: <Profile key={userId} />, which makes React create a fresh instance.
Responding to a user action. Showing a toast after "Add to cart", sending a POST request after submit, or navigating after saving all belong in the click or submit handler. Putting them in an effect that watches cart re-fires whenever the dependency changes for any reason (including reload or navigation back).
Chains of effects. One effect sets state which triggers another effect and so on. Calculate everything in the handler or during render.
Notifying parents. Instead of an effect calling onChange(value) when state changes, call onChange in the same handler that updates state, so both updates are batched.
Initializing the app (once). Code that must run once per page load, not per component mount, can go at module level or in an entry file. Strict Mode runs effects twice in development, which exposes this issue.
Subscribing to external stores. Use useSyncExternalStore, not an effect with state.
Cases where an effect is right: synchronizing with a network connection, a timer, a browser API such as the document title or a map widget, analytics events for displaying a screen (page view), and fetching data when no data library or framework handles it.
A good test: "Why does this code run?" If the answer is "because the user clicked", use a handler. If "because the component is shown or a value it displays changed and I must sync with an external system", use an effect.
The example puts the cart logic in the handler and calculates the total in render.
jsx
import { useState } from 'react';
const PRICES = { Pen: 20, Book: 150 };
export default function Cart() {
const [items, setItems] = useState([]);
const [toast, setToast] = useState('');
// Derived during render: no extra state, no effect.
const total = items.reduce((sum, name) => sum + PRICES[name], 0);
function addItem(name) {
setItems([...items, name]);
// A response to the user's click belongs in the handler, not in an effect that watches items.
setToast(name + ' added');
console.log('toast: ' + name + ' added');
}
return (
<div>
<button onClick={() => addItem('Pen')}>Add Pen</button>
<button onClick={() => addItem('Book')}>Add Book</button>
<p>
{items.length} items, total {total}
</p>
<output>{toast}</output>
</div>
);
}
The check added a pen twice and a book once. Each toast is created exactly once, in the click that caused it, and the total is always consistent with the items because it is not separate state. Output of the run:
toast: Pen added
toast: Pen added
toast: Book added
summary: 3 items, total 190
Key points
Handlers respond to user actions. Effects synchronize with external systems.
Calculate derived values during render instead of storing them with an effect.
Reset state with a key instead of an effect watching a prop.
Avoid effect chains and effects that only notify parents. Update everything in one handler.
Use effects for subscriptions, timers, network and browser API synchronization.
Common mistakes
Using an effect to copy props or state into other state.
Running a POST request in an effect that watches form data instead of in the submit handler.
Chaining several effects that each set state for the next one.
Calling onChange from an effect, which creates an extra render pass.
Using effects for one-time app initialization and then seeing it run twice in development.
Follow-ups
How does a key help reset state without an effect?
When is fetching data in an effect still reasonable?
Why does an effect that notifies the parent cause an extra render?
Tips
Use the question "why does this code run?". It is a memorable test.
List three cases without effects: derived data, reset with key, user actions.
Say what effects are good for, so you do not sound against them.
120.react-0120Mediummid
What are the common derived-state anti-patterns in React (copying props into state, storing computed values), and how do you fix them?
Derived state is data you can compute from other state or props. Storing it separately creates a second source of truth that can fall out of sync. The common mistakes are copying a prop into state (it ignores later prop changes), storing filtered or sorted lists in state, and syncing them with effects. Compute the value during render, store only the minimal state (such as the query and the selected id), and use a key to reset state intentionally.
Full answer
Every extra piece of state is something you must keep consistent. When one value can be calculated from another, store the source and calculate the rest.
Anti-pattern 1: mirroring a prop in state. const [name, setName] = useState(props.name) reads the prop only on the first render, so when the parent passes a new name the component still shows the old one. Fix options: use the prop directly (a controlled component), or if the component really needs an editable draft, name the prop initialName, and reset with key when the source changes (<Editor key={user.id} initialName={user.name} />).
Anti-pattern 2: storing computed data. Keeping filteredCourses in state and updating it in onChange or in an effect doubles the state, and any path that updates courses without updating filteredCourses leaves them inconsistent. Store the courses and the query, then compute const visible = courses.filter(...) in render. If the computation is slow, wrap it in useMemo after measuring, or let the React Compiler memoize it.
Anti-pattern 3: storing objects that duplicate others. const [selectedCourse, setSelectedCourse] = useState(course) copies the object, which goes stale if the list item is edited. Store the selectedId and derive the object with find.
Anti-pattern 4: syncing with effects. useEffect(() => setTotal(items.length * price), [items, price]) renders twice and briefly shows a wrong total. Compute it in render.
When copying is fine: you want a snapshot or a draft that intentionally diverges from the source (a form being edited), and you document and reset it.
A guideline: store the minimum state that cannot be computed, and avoid redundant, contradicting or duplicated state.
The example stores only the query and the selected id, and derives the rest.
The component stores only the query and the selected id. The check typed "sci", and the list and the count followed it with no effects and no duplicate state. Output of the run:
start: Science basics, Maths basics, Science advanced | 3 of 3 shown, selected: none
after typing sci: Science basics, Science advanced | 2 of 3 shown, selected: none
Key points
Derived state is anything you can compute from existing state or props. Compute it during render.
Copying a prop into useState ignores later prop changes. Use the prop, or name it initial and reset with a key.
Store ids instead of copies of objects, and derive the object with find.
Do not sync derived values with effects. It adds renders and flashes of wrong data.
Copying is acceptable for drafts that intentionally diverge from the source.
Common mistakes
Writing useState(props.value) and expecting it to follow prop changes.
Storing filtered or sorted arrays in state.
Storing a copy of a selected object instead of its id.
Using useEffect to keep two pieces of state in sync.
Wrapping every derived value in useMemo without measuring.
Follow-ups
How would you build an editable form that starts from server data and resets on navigation?
When is useMemo appropriate for derived data?
How does the React Compiler affect this advice?
Tips
Say "single source of truth" and "minimal state".
Give the id instead of object example. It is easy to remember.
Mention the key reset as the clean fix for drafts.