React Fundamentals

Components and JSX, props, rendering lists with keys, conditional rendering, events, composition with children, the virtual DOM and reconciliation, and thinking in React.

Intermediate 4 min readLesson 6 of 14 Interview Q&A

React is a library for building user interfaces from components: functions that take data and return a description of UI. Instead of telling the DOM how to change step by step, you declare what the UI should look like for the current state, and React figures out the minimal DOM updates.

UI = f(state)

Components and JSX

TSX
type Props = { name: string; avatarUrl: string; online?: boolean };

function UserCard({ name, avatarUrl, online = false }: Props) {
  return (
    <div className="user-card">
      <img src={avatarUrl} alt="" width={48} height={48} />
      <h3>{name}</h3>
      {online && <span className="badge">Online</span>}
    </div>
  );
}

// Usage
<UserCard name="Asha" avatarUrl="/a.png" online />

JSX is syntax sugar that compiles to function calls creating plain objects (React elements):

JavaScript
// <h3 className="title">{name}</h3>   compiles to:
jsx("h3", { className: "title", children: name })
// → { type: "h3", props: { className: "title", children: "Asha" } }

JSX rules: one root element (or a <>…</> fragment); className instead of class; htmlFor instead of for; camelCase attributes (onClick, tabIndex); {expression} embeds JavaScript; every tag must close. Values in {…} are escaped, which protects against XSS.

Props

Props are a component's inputs, passed by the parent. They're read-only: a component must never modify its props. Data flows down the tree; to send information up, parents pass callbacks:

TSX
function Counter({ value, onIncrement }: { value: number; onIncrement: () => void }) {
  return <button onClick={onIncrement}>Clicked {value} times</button>;
}

Composition with children

TSX
function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="card">
      <h2>{title}</h2>
      {children}
    </section>
  );
}

<Card title="Billing">
  <p>Next invoice: 1 January</p>
  <Button>Update card</Button>
</Card>

React favours composition over inheritance: specialise components by wrapping them and passing children or props, not by subclassing.

Lists and keys

TSX
function TodoList({ todos }: { todos: Todo[] }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>       // key: a stable, unique id
      ))}
    </ul>
  );
}

Keys tell React which item is which between renders, so it can move, insert and delete DOM nodes correctly and preserve each item's state. Use stable IDs — not array indices when the list can be reordered, filtered or inserted into (indices would attach state to the wrong item).

Conditional rendering

TSX
{isLoading ? <Spinner /> : <Results items={items} />}
{error && <ErrorBanner message={error} />}
{items.length > 0 ? <List items={items} /> : <EmptyState />}   // not {items.length && …}, which renders 0

Events

TSX
function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
  return (
    <form onSubmit={e => { e.preventDefault(); onSearch(new FormData(e.currentTarget).get("q") as string); }}>
      <input name="q" />
      <button type="submit">Search</button>
    </form>
  );
}

Pass a function, not a call: onClick={handleClick}, not onClick={handleClick()}.

Rendering, the virtual DOM and reconciliation

When state changes, React re-renders: it calls the affected component functions again to get a new element tree, then reconciles it with the previous tree and applies only the differences to the real DOM.

  1. Trigger: initial render, or a state update (setState).
  2. Render: call component functions to produce a new tree of elements (pure — no DOM work yet).
  3. Reconcile (diff): compare with the previous tree to find what changed.
  4. Commit: apply the minimal DOM mutations; run effects.

Diffing two arbitrary trees is O(n³); React uses heuristics to make it O(n):

  1. Elements of different types (<div> → <span>, <A> → <B>) produce entirely new subtrees — the old subtree and its state are destroyed.
  2. Same type: keep the DOM node, update changed attributes, recurse into children.
  3. Children lists are matched by key.

"Virtual DOM" just means this in-memory tree of plain objects. It's not inherently faster than hand-written DOM code; its value is letting you write declarative UI while React handles efficient updates. (Some frameworks — Svelte, Solid — skip the virtual DOM by compiling components into fine-grained updates.)

Fiber, React's reconciler, splits rendering into interruptible units so urgent updates (typing) can pre-empt less urgent ones (rendering a big list) — the basis of concurrent features like useTransition.

Thinking in React

  1. Break the UI into a component hierarchy (each does one thing).
  2. Build a static version with props only.
  3. Find the minimal state (anything derivable from other state or props isn't state).
  4. Decide where state lives: the closest common parent of the components that need it ("lifting state up").
  5. Add inverse data flow: pass callbacks down so children can request changes.
Key takeaways
  • React components are functions from props/state to UI; JSX compiles to element objects.
  • Props flow down and are read-only; callbacks send events up; children enable composition.
  • Lists need stable keys so React can match items and preserve state.
  • Re-render → reconcile (O(n) heuristic diff by type and key) → commit minimal DOM changes.
  • Keep components pure; find minimal state and lift it to the closest common parent.
Interview questions
QWhy does React need keys in lists?easy

Keys give each list item a stable identity across renders. During reconciliation React matches old and new children by key, so it can move, insert or remove the corresponding DOM nodes and keep each component's state attached to the right item. Using array indices as keys breaks this when the list is reordered or filtered — state and DOM nodes end up associated with the wrong items.

QWhat is the virtual DOM and why use it?medium

It's React's in-memory tree of plain JavaScript objects describing the UI. On each update React renders a new tree, diffs it against the previous one using heuristics (different element types replace subtrees; keys match list items), and applies only the necessary real DOM changes. The benefit is a declarative programming model with reasonably efficient updates — not raw speed over well-written imperative DOM code.