Appearance
React Basics
1. What is React and why use it?
The short answer
React is a JavaScript library for building user interfaces out of components: small, reusable functions that take data and return a description of what the screen should look like. You describe the UI for the current state, and when the state changes, React works out the smallest set of changes to the real page and applies them. That makes complex, interactive screens easier to build, reason about and reuse, compared with changing the page by hand.
The problem React solves. Without React, you update the page by hand: find the element, change its text, add a class, remove a row. With many moving parts, such as a cart badge, a total, a checkout button and a list of items, it is easy to forget one, and the screen ends up showing two different truths.
React's idea: UI is a function of state.
tsx
function CartBadge({ count }: { count: number }) { // (1)
return (
<span className={count > 0 ? 'badge active' : 'badge'}> {/* (2) */}
{count} items
</span>
)
}- A component is a function. It receives data, called props.
- It returns what the UI should look like for that data. You never write "change the badge to 3". You say "for 3 items, the badge looks like this", and React keeps the page in step.
Why teams choose it:
| Reason | What it means |
|---|---|
| Components | Build a ProductCard once, use it everywhere |
| Declarative | Describe the result, not the steps to get there |
| Efficient updates | React changes only what actually differs (question 4) |
| Ecosystem | Routing, data fetching, forms, state libraries, testing tools, all mature |
| One model, many targets | Web, and mobile with React Native |
| Hiring | It is the most widely used UI library, so the skills are common |
A library, not a framework. React only does the UI layer. Routing, data fetching and building are done by other tools: Vite builds the app (question 54), React Router or TanStack Router handle URLs, and TanStack Query fetches data (question 47). Frameworks such as Next.js bundle these choices together (question 64).
Current version. React 19 arrived in December 2024 and React 19.2 in October 2025, adding features such as Actions, the use hook and <Activity>. The React Compiler, which memoises components automatically, became stable in late 2025 (question 25).
2. What is JSX and what does it compile to?
The short answer
JSX is a syntax extension that lets you write HTML-like tags inside JavaScript, such as <Button size="lg">Pay</Button>. Browsers cannot run it, so a build tool turns each tag into a function call, jsx(Button, { size: 'lg', children: 'Pay' }), which creates a plain JavaScript object describing that element. Because JSX is JavaScript, you can put any expression inside curly braces, but statements such as if and for must be turned into expressions, such as &&, ternaries and map.
What you write, and what runs:
tsx
// What you write
const button = <button className="pay" disabled={!ready}>Pay £{total}</button>
// Roughly what the build turns it into
import { jsx } from 'react/jsx-runtime'
const button2 = jsx('button', { className: 'pay', disabled: !ready, children: ['Pay £', total] })That call returns a small object, a React element, such as { type: 'button', props: { ... } }. React uses these objects to build and update the real page (question 8).
Rules that trip people up:
| Rule | Why |
|---|---|
className, not class | class is a reserved word in JavaScript |
htmlFor, not for | Same reason |
| One root element | A function returns one value; use <>…</>, a Fragment, to group |
| Close every tag | <img />, <br /> |
{} for expressions | {total.toFixed(2)}, not statements |
style takes an object | style={ { color: 'red' } }: outer braces for the expression, inner for the object, usually written without the spaces |
| Lower-case tags are HTML, capitalised are components | <button> versus <Button> |
Conditionals and lists, as expressions:
tsx
function OrderSummary({ items, isVip }: { items: { sku: string; name: string }[]; isVip: boolean }) {
return (
<>
{isVip && <p className="vip">Free delivery</p>} {/* (1) */}
{items.length === 0 ? <p>Your basket is empty</p> : ( /* (2) */
<ul>
{items.map((item) => <li key={item.sku}>{item.name}</li>)} {/* (3) */}
</ul>
)}
</>
)
}&&shows the element only when the condition is true.- A ternary chooses between two elements.
mapturns data into a list of elements, each with akey(question 5).
A trap with &&: {count && <Badge />} prints 0 on the page when count is 0, because 0 is falsy and React renders numbers. Write {count > 0 && <Badge />}.
JSX is safe by default. Values in {} are escaped, so {userComment} shows text, never runs it as HTML (question 37).
3. What is the difference between props and state?
The short answer
Props are inputs a component receives from its parent, like function arguments; the component must not change them. State is data a component owns and can change over time, with useState or useReducer; changing it makes React render the component again. A simple test: if the value comes from outside, it is a prop; if the component itself must remember and change it, it is state. A parent's state is often passed down as a child's props.
tsx
function QuantityPicker({ max, onChange }: { max: number; onChange: (q: number) => void }) { // (1)
const [qty, setQty] = useState(1) // (2)
function increase() {
const next = Math.min(qty + 1, max)
setQty(next) // (3)
onChange(next) // (4)
}
return <button onClick={increase}>Qty: {qty}</button>
}
function ProductPage() {
const [quantity, setQuantity] = useState(1)
return <QuantityPicker max={10} onChange={setQuantity} /> // (5)
}- Props:
maxandonChangecome from the parent.QuantityPickerreads them but never changes them. - State:
qtybelongs to this component and starts at1. - Updating state tells React to render this component again with the new value.
- A callback prop is how a child tells its parent something happened.
- The parent's state becomes the child's prop.
| Props | State | |
|---|---|---|
| Comes from | The parent | The component itself |
| Can the component change it? | No, read-only | Yes, with its setter |
| Changing it causes a re-render | When the parent passes a new value | Yes |
| Like | Function arguments | Variables the function remembers between calls |
Do not copy props into state unless you want only the first value. const [name, setName] = useState(props.name) ignores later changes to props.name. Use the prop directly, or compute from it during render.
Derived values are not state. If something can be calculated from props or other state, such as a cart total from the items, calculate it during render instead of storing it. Storing it means two copies that can disagree.
4. What is the virtual DOM, and how does reconciliation work?
The short answer
The virtual DOM is React's lightweight description of the UI: a tree of plain JavaScript objects, the elements your components return. When state changes, React calls the affected components again to get a new tree, compares it with the previous one, a process called reconciliation, and then makes only the necessary changes to the real browser DOM. Comparing objects in memory is cheap; touching the real DOM is slow, so this keeps updates efficient while you write simple "describe the whole UI" code.
The steps, when you call setItems:
- Trigger: a state update marks the component as needing to render.
- Render: React calls the component function, and its children, to get new elements. This is pure calculation; nothing on the page changes yet.
- Reconcile: React compares the new elements with the previous ones.
- Commit: React applies the differences to the real DOM, then runs effects (question 13).
The rules that make comparison fast. A perfect comparison of two trees is very slow, so React uses two shortcuts:
| Rule | Effect |
|---|---|
| Different element type at the same position | Throw away the old subtree and build a new one, including its state |
| Same type | Keep the DOM node and its state, update only the changed attributes |
| Lists | Match children by key, not by position (question 5) |
A consequence worth knowing: switching between <CheckoutForm /> and <div><CheckoutForm /></div> at the same position changes the type of the wrapping element, so React throws the form away and its typed-in values are lost.
"Virtual DOM" is a simplification. Internally, React keeps a tree called the Fiber tree, which also lets it split rendering into small units and pause for more urgent work, such as typing (question 27).
5. Why do list items need keys?
The short answer
Keys tell React which item in a list is which between renders. Without stable keys, React matches items by position, so when you insert, remove or reorder items, it may update the wrong DOM nodes and keep the wrong component state, such as text typed in an input, attached to the wrong row. A key must be stable and unique among its siblings, usually an ID from your data. Array indexes are only safe for lists that never change order.
The bug that index keys cause:
tsx
function CartLines({ lines }: { lines: { id: string; name: string }[] }) {
return (
<ul>
{lines.map((line, i) => (
<li key={i}> {/* (1) wrong */}
{line.name} <input placeholder="gift note" />
</li>
))}
</ul>
)
}- Keyed by position. You type "Happy birthday" into the gift note of the first line, then remove the first line. React sees keys
0and1before, and only0after, so it thinks item1was removed, and keeps the input of item0. Your note now sits on the wrong product.
The fix:
tsx
{lines.map((line) => (
<li key={line.id}> {/* stable identity */}
{line.name} <input placeholder="gift note" />
</li>
))}Now React knows exactly which line was removed, and the other inputs keep their text.
| Key choice | Safe? |
|---|---|
| A database ID, SKU, or other stable unique value | Yes |
| Array index | Only for static lists that never reorder, insert or delete |
Math.random() or crypto.randomUUID() during render | No: a new key each render destroys and rebuilds every item |
Keys are also a reset button. Changing a component's key makes React treat it as a new component and reset its state. <ProfileForm key={userId} /> gives every user a fresh form without writing any reset code.
6. What is the difference between controlled and uncontrolled components?
The short answer
In a controlled input, React state is the single source of truth: the input's value comes from state, and every keystroke goes through onChange to update that state. In an uncontrolled input, the browser's DOM keeps the value, and you read it when needed, with a ref or from the form when it is submitted. Controlled inputs make live validation and formatting easy; uncontrolled ones are simpler and re-render less, which form libraries such as React Hook Form use for speed.
tsx
function PromoCodeControlled() {
const [code, setCode] = useState('') // (1)
return (
<input
value={code} // (2)
onChange={(e) => setCode(e.target.value.toUpperCase())} // (3)
/>
)
}
function NewsletterUncontrolled() {
const emailRef = useRef<HTMLInputElement>(null) // (4)
function onSubmit(e: React.FormEvent) {
e.preventDefault()
subscribe(emailRef.current!.value) // (5)
}
return (
<form onSubmit={onSubmit}>
<input ref={emailRef} defaultValue="" type="email" /> {/* (6) */}
<button>Subscribe</button>
</form>
)
}- State holds the value.
- The input shows exactly what state says.
- Every change goes through your code, so you can transform it, here to upper case, or validate it.
- A ref points at the DOM input (question 16).
- Read the value only when needed, on submit.
defaultValuesets the starting value once; after that the browser owns it.
| Controlled | Uncontrolled | |
|---|---|---|
| Source of truth | React state | The DOM |
| Re-render per keystroke | Yes | No |
| Live validation, formatting, dependent fields | Easy | Harder |
| Code needed | More | Less |
| Use for | Inputs that drive other UI | Simple forms, file inputs, very large forms |
The warning you will see: "A component is changing an uncontrolled input to be controlled". It happens when value starts as undefined and later becomes a string. Always start controlled inputs with a defined value, such as ''.
File inputs are always uncontrolled, because their value can only be set by the user, for security.
7. What is one-way data flow, and what does lifting state up mean?
The short answer
In React, data flows down: a parent passes data to its children as props, and children cannot change their parent's data directly. To change it, a child calls a function the parent passed down. When two sibling components need the same changing data, you move that state up to their nearest common parent, which passes it down to both. That is lifting state up, and it keeps one source of truth instead of two copies that can disagree.
tsx
function Checkout() {
const [coupon, setCoupon] = useState<string | null>(null) // (1)
return (
<>
<CouponForm onApply={setCoupon} /> {/* (2) */}
<Summary coupon={coupon} /> {/* (3) */}
</>
)
}
function CouponForm({ onApply }: { onApply: (code: string) => void }) {
const [text, setText] = useState('')
return (
<form onSubmit={(e) => { e.preventDefault(); onApply(text) }}> {/* (4) */}
<input value={text} onChange={(e) => setText(e.target.value)} />
</form>
)
}- The state lives in the common parent, because both children need it.
- The form gets a function, not the state itself.
- The summary gets the value.
- The form reports upward by calling the function; it never reaches into the parent.
Why one direction? When something on screen is wrong, you can trace it: the value came from props, which came from one parent's state, which changed in one place. With two-way binding, anything could have changed it.
When lifting goes too far, such as passing a prop through five layers that do not use it, that is prop drilling (question 39).
8. What is the difference between a component and an element?
The short answer
A component is the function, or class, you write: function ProductCard(props) { … }. An element is the plain object that describes one instance of it on screen, created when you write <ProductCard id="p1" />. Components are recipes; elements are the orders placed from them. React calls your component functions to get elements, and turns elements into real DOM nodes. Today almost all React code uses function components with hooks rather than class components.
tsx
function ProductCard({ name }: { name: string }) { // a component: a function
return <h3>{name}</h3>
}
const el = <ProductCard name="Teapot" /> // an element: a description
console.log(el.type === ProductCard) // true
console.log(el.props) // { name: 'Teapot' }Function versus class components:
| Function component | Class component | |
|---|---|---|
| State | useState, useReducer | this.state, this.setState |
| Side effects | useEffect | componentDidMount, componentDidUpdate, componentWillUnmount |
| Reusing logic | Custom hooks (question 20) | Higher-order components, render props |
| Today | The standard | Legacy, but still in old codebases |
The one thing still needing a class is an error boundary, unless you use a library such as react-error-boundary (question 30).
Calling a component directly is a mistake: {ProductCard({ name })} runs it as an ordinary function, so React does not see it as a component, and any hooks inside it attach to the parent instead. Always render with JSX.
9. How do events work in React?
The short answer
You attach handlers with camelCase props such as onClick and onChange, passing a function, not calling one. React gives the handler a synthetic event, a wrapper around the browser's native event with the same interface across browsers. React does not attach a listener to every element; it listens once at the root of your app and dispatches events to the right handlers. Call e.preventDefault() to stop default behaviour such as a form submitting.
tsx
function AddToCart({ sku, onAdd }: { sku: string; onAdd: (sku: string, qty: number) => void }) {
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault() // (1)
const qty = Number(new FormData(e.currentTarget).get('qty'))
onAdd(sku, qty)
}
return (
<form onSubmit={handleSubmit}> {/* (2) */}
<input name="qty" type="number" defaultValue={1} min={1} />
<button type="submit">Add</button>
<button type="button" onClick={() => onAdd(sku, 1)}>Quick add</button> {/* (3) */}
</form>
)
}- Stop the browser's default action, which for a form is a full page reload.
- Pass the function itself.
onSubmit={handleSubmit()}would call it during render, every render. - An inline arrow when you need to pass extra arguments.
Things interviewers check:
e.targetversuse.currentTarget:targetis the element actually clicked, which may be a child;currentTargetis the element the handler is attached to.stopPropagation()stops the event bubbling to parent handlers. Use it rarely, because it breaks other code that listens higher up.- Event delegation: since React 17, React attaches its listeners to the root container of your app, not to
document, so several React apps on one page do not interfere.
10. What does React StrictMode do?
The short answer
<StrictMode> is a development-only wrapper that helps you find bugs early. It renders components twice, runs effects twice by mounting, unmounting and mounting again, and warns about deprecated APIs. That surfaces impure render functions and effects without proper cleanup, which would otherwise cause subtle bugs. It has no effect in production builds, so the double calls you see in development never happen for real users.
tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)What it checks, and the bug each catches:
| Check | Catches |
|---|---|
| Renders each component twice | Render code with side effects, such as changing a variable outside the component |
| Mounts, unmounts and remounts effects | Effects that subscribe or connect but never clean up (question 14) |
| Warns about deprecated APIs | Old patterns that will break in future versions |
Why the double effect is useful. In real use, components mount and unmount all the time: navigating away and back, or a list item scrolling out and in. An effect that opens a WebSocket but has no cleanup leaks one connection each time. StrictMode makes the leak visible immediately, as two connections, in development.
Do not remove StrictMode to make a double request go away. Fix the effect instead, usually with a cleanup function or by moving data fetching to a library that handles it (question 38).