React · Lesson 1

Components & props

Components as plain functions from props to UI, what JSX really is, typing props in TypeScript (required and optional, children, unions, generics), composition instead of inheritance, and lists with keys.

13 min read

In short

  • Components are pure functions from props to UI
  • JSX compiles to small { type, props } objects
  • Type props with literal unions and ReactNode
  • Write count > 0 &&, not count &&
  • Keys are identity: stable ids, never index or random

On a React team, most of your day is writing components and reading other people's. A component is a plain function: it takes props and returns a description of the UI. TypeScript checks every place the component is used, so a good props type is also the component's documentation. Get the props right and invalid usages don't compile. Get them wrong and every caller has to guess.

This lesson builds the mental model you'll lean on in every later topic: JSX is just objects, components are functions, props are types, and keys are identity. The React snippets show real code and can't run here. The plain TypeScript snippets rebuild the mechanism and have a ▶ Try button.

A component is a function

import type { ReactNode } from 'react';

type GreetingProps = {
  name: string;
  children?: ReactNode;
};

export function Greeting({ name, children }: GreetingProps) {
  return (
    <section className="greeting">
      <h1>Hello, {name}!</h1>
      {children}
    </section>
  );
}

// Somewhere else:
<Greeting name="Ann">
  <p>You have 3 new messages.</p>
</Greeting>;

The rules that matter:

  • Capital letter. <Greeting /> refers to your function. <greeting /> would be an HTML tag called greeting, because JSX treats lowercase names as built-in elements.
  • React calls it, you don't. Write <Greeting name="Ann" />, never Greeting({ name: 'Ann' }). Calling it yourself skips React, so hooks inside it break and React can't track its state.
  • It must be pure. Same props and state in, same output out. No fetch, no timers, no changing variables outside the function while rendering. Side effects belong in event handlers or effects (see the Effects topic). React may call your component more often than you expect: in development, Strict Mode calls it twice on purpose to catch impure renders.
  • Props are read-only. Never assign to props.x or push into an array you received. If something needs to change, it's state (next topic), and the owner of the state changes it.
  • JSX is not HTML. className instead of class, htmlFor instead of for, style={{ fontSize: 12 }} (an object), camelCase events (onClick), every tag closed (<br />), and { } embeds any JavaScript expression.

JSX is just objects

JSX is syntax for function calls. With the automatic runtime (React 17 and later), the compiler turns

import { jsx } from 'react/jsx-runtime';

const link = <a href="/docs" className="nav-link">Docs</a>;
// becomes
const same = jsx('a', { href: '/docs', className: 'nav-link', children: 'Docs' });

and jsx returns a small, immutable object: roughly { type, key, props }. The type is a string for HTML elements and your function for components. Creating an element does not call the component. React calls it later, when it renders that part of the tree:

▶ Try
type Props = Record<string, unknown>;
type El = { type: string | ((props: any) => unknown); props: Props };

function jsx(type: El['type'], props: Props): El {
  return { type, props };
}

let renders = 0;
function Greeting(props: { name: string }) {
  renders++;
  return jsx('h1', { children: ['Hello, ', props.name] });
}

const tree = jsx(Greeting, { name: 'Ann' });
console.log('type is the function itself:', tree.type === Greeting, '| renders so far:', renders);

// What React does when it renders that element:
const output = (tree.type as typeof Greeting)(tree.props as { name: string });
console.log(JSON.stringify(output), '| renders so far:', renders);

After rendering, React compares the new tree of objects with the previous one (reconciliation) and changes only the DOM nodes that differ. That's why returning a whole new tree on every render is cheap enough: the objects are tiny, and the DOM work is what costs.

What renders, and what doesn't

You returnReact shows
a string or a numbertext, escaped (so {userInput} can't inject HTML)
null, undefined, true, falsenothing
an arrayeach item, in order (each needs a key)
an elementthat element

The table explains the most common JSX bug:

import type { ReactNode } from 'react';

function Inbox({ count }: { count: number }): ReactNode {
  return <div>{count && <Badge count={count} />}</div>;
  // count = 0 renders "0", because `0 && x` is 0 and numbers render.
  // Fix: {count > 0 && <Badge count={count} />}  or  {count ? <Badge count={count} /> : null}
}

Exercise 1 builds this table as a small renderToString.

Typing props

Props are an ordinary object type. Destructure them in the parameter list, and give optional props their default right there:

import type { ReactNode } from 'react';

type BadgeProps = {
  label: string;                                // required
  tone?: 'neutral' | 'success' | 'danger';      // optional, and only these three values
  count?: number;                               // optional; undefined when not passed
  icon?: ReactNode;                             // anything renderable: element, string, null...
  onDismiss?: (label: string) => void;          // a callback prop
};

export function Badge({ label, tone = 'neutral', count, icon, onDismiss }: BadgeProps) {
  return (
    <span className={`badge badge-${tone}`}>
      {icon}
      {label}
      {count !== undefined && <strong>{count}</strong>}
      {onDismiss && <button onClick={() => onDismiss(label)} aria-label={`Dismiss ${label}`}>×</button>}
    </span>
  );
}
  • Literal unions, not string. tone?: string accepts 'dagner'. A union catches the typo at the call site, and the editor autocompletes the options.
  • ReactNode is the type for "something React can render": elements, strings, numbers, null, undefined, booleans and arrays of those. Use it for children and for slot props like icon.
  • children is a normal prop. Declare it when you accept it: children: ReactNode if required, children?: ReactNode if not. PropsWithChildren<P> adds the optional version for you. React.FC<P> still works, but it no longer adds children implicitly, and most teams now type the parameter directly.
  • Callback props are named onSomething and take the data the parent needs (onDismiss(label)), not the raw DOM event, unless the parent really needs the event. For DOM events, React has typed events: (e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value).
  • Wrapping a native element. ComponentProps<'button'> is every prop a <button> accepts. Intersect it with your own and spread the rest. The React & Angular patterns topic of the TypeScript track covers this, with Omit for taking over a native prop.
  • ref is a prop (React 19). Function components receive ref like any other prop, so forwardRef isn't needed in new code:
import type { ComponentProps } from 'react';

type TextInputProps = ComponentProps<'input'> & { label: string };

export function TextInput({ label, ref, ...input }: TextInputProps) {
  return (
    <label>
      {label}
      <input ref={ref} {...input} />
    </label>
  );
}

Props that depend on each other

When some props only make sense together, a bag of optional props lets every wrong combination compile. Use a union instead. The TypeScript track's React & Angular patterns topic shows variant props (kind: 'link' | 'button'). Here is the other everyday case: a prop that must not be passed with another one. ?: never says "this prop is not allowed here":

// TextField.tsx (not runnable here)
type TextFieldProps = { label: string } & (
  | { value: string; onChange: (value: string) => void; defaultValue?: never }   // controlled
  | { value?: never; defaultValue?: string; onChange?: (value: string) => void }  // uncontrolled
);

<TextField label="Name" value={name} onChange={setName} />;   // ok
<TextField label="Name" defaultValue="Ann" />;                // ok
<TextField label="Name" defaultValue="Ann" onChange={log} />; // ok: uncontrolled, just listening
<TextField label="Name" value={name} />;                      // ✗ value without onChange
<TextField label="Name" value={name} onChange={setName} defaultValue="x" />; // ✗ both modes

This matches React's own two modes for form inputs:

  • Controlled: the input shows exactly value. Typing calls onChange, and nothing changes on screen until the parent stores the new value and re-renders. The parent owns the state, so it can validate, format or reject input.
  • Uncontrolled: the input keeps its own state. defaultValue is read once, on mount. Later changes to defaultValue are ignored.

Switching from one mode to the other during the component's life is a bug React warns about ("A component is changing an uncontrolled input to be controlled"). The usual cause is state that starts as undefined: value={undefined} means uncontrolled. Exercise 3 builds a field with both modes.

Generic components

A component can be generic, just like a function. TypeScript infers T from the props, so the callbacks are typed without any annotations at the call site:

import type { ReactNode } from 'react';

type SelectProps<T> = {
  options: readonly T[];
  value: T | null;
  getKey: (option: T) => string;
  getLabel: (option: T) => string;
  onChange: (option: T) => void;
};

export function Select<T>({ options, value, getKey, getLabel, onChange }: SelectProps<T>) {
  const selectedKey = value === null ? '' : getKey(value);
  return (
    <select value={selectedKey} onChange={(e) => onChange(options.find((o) => getKey(o) === e.target.value)!)}>
      <option value="" disabled>Choose…</option>
      {options.map((o) => <option key={getKey(o)} value={getKey(o)}>{getLabel(o)}</option>)}
    </select>
  );
}

<Select options={users} value={owner} getKey={(u) => u.id} getLabel={(u) => u.name} onChange={setOwner} />;
// T = User: `u` is a User, and onChange must accept a User

A data table is the classic case. With a mapped type, each column's render receives the type of that column's field, so { key: 'createdAt', render: (d) => d.toLocaleDateString() } knows d is a Date. Exercise 5 builds exactly that. In a .tsx file, a generic arrow function needs a comma, const List = <T,>(props: ListProps<T>) => ..., so the parser doesn't read <T> as a JSX tag.

Composition instead of inheritance

React components never extend each other. You build bigger components by putting components inside components:

import type { ComponentProps, ReactNode } from 'react';

type CardProps = { title: string; actions?: ReactNode; children: ReactNode };

export function Card({ title, actions, children }: CardProps) {
  return (
    <article className="card">
      <header>
        <h2>{title}</h2>
        {actions && <div className="card-actions">{actions}</div>}
      </header>
      <div className="card-body">{children}</div>
    </article>
  );
}

// Specialization by wrapping, not by subclassing:
export function DangerButton(props: Omit<ComponentProps<'button'>, 'className'>) {
  return <button {...props} className="btn btn-danger" />;
}

<Card title="Billing" actions={<DangerButton onClick={cancelPlan}>Cancel plan</DangerButton>}>
  <InvoiceList customerId={customerId} />
</Card>;
  • children and slot props (actions, icon, header) let the caller decide what goes inside. Card doesn't know about invoices, and it doesn't need a prop for every possible variation.
  • Passing elements down is also the first fix for "prop drilling". If Page needs a user only to hand it to a deeply nested Avatar, let Page's caller build <Avatar user={user} /> and pass the element down as a slot. The Context topic covers the cases where that's not enough.
  • Behaviour as props. Headless libraries such as React Aria and Downshift hand you behaviour as a props object to spread: const { buttonProps } = useButton(options, ref). When two of them both need onKeyDown, or you add your own className, merge the objects so handlers are chained instead of the last one silently winning. Exercise 6 builds that mergeProps.
  • If you know Angular: props are input(), callback props are output(), children is <ng-content>, and named slots are <ng-content select="[actions]">.

Lists and keys

import type { Todo } from './types';

export function TodoList({ todos }: { todos: readonly Todo[] }) {
  return (
    <ul>
      {todos.map((todo) => (
        <TodoItem key={todo.id} todo={todo} />
      ))}
    </ul>
  );
}

A key tells React which item is which between renders. React matches the new children to the old ones by key (and type). A match keeps the same component instance: its state, its DOM node and its effects. No match means unmount the old one and mount a new one.

  • Keys must be unique among siblings and stable: use the id from your data.
  • Index keys break as soon as the list is reordered, filtered or added to anywhere except the end. The state stays with the position, not the item:
▶ Try
// Each row keeps some state: here, the text typed into its input.
const oldRows = ['Bob', 'Cy'];
const typedText = ['call back Monday', ''];   // state of the old row instances, in order
const newRows = ['Ann', 'Bob', 'Cy'];         // Ann was inserted at the top

for (const [i, name] of newRows.entries()) {
  console.log(`key=index  ${name}: "${typedText[i] ?? ''}"`);   // matched by position
}
for (const name of newRows) {
  const old = oldRows.indexOf(name);                            // matched by key
  console.log(`key=name   ${name}: "${old === -1 ? '' : typedText[old]}"`);
}
  • Random keys (key={Math.random()}) are worse: nothing ever matches, so every row remounts on every render and loses its state and focus.
  • key is not a prop. TodoItem can't read props.key. Pass the id separately if the child needs it.
  • When map returns several elements per item, put the key on a <Fragment key={item.id}>.
  • A new key resets a component. <ProfileForm key={userId} userId={userId} /> throws away the form's state whenever the user changes. It's the standard way to reset state without an effect.

React's matching is fast but simple. It walks the new list once and leaves an item in place when its old position comes after the last item it left in place. Everything else moves. So moving the last item to the front moves every other item, while moving the first item to the end moves just one. Exercise 4 builds the matching step, and the Performance topic's "Keyed list reconciliation" exercise rebuilds the moves.

Common mistakes

  • {count && ...} rendering 0. Compare explicitly: count > 0 &&.
  • Defining a component inside another component. function Row() {} written inside Table is a new function on every render, so React sees a new type each time, unmounts the old Rows and mounts new ones. State and focus are lost on every keystroke. Define components at the top level.
  • Calling a component as a function, or mutating props.
  • tone?: string where a union of literals would catch typos.
  • Optional props that only make sense together (value and onChange) instead of a union.
  • Index or random keys in lists that change.
  • Copying a prop into state (useState(props.initialName)) and expecting it to follow the prop. It doesn't. The State topic explains why, and what to do instead.

In a real codebase

Side note
  • One component per file, exporting the component and its props type (Button.tsx exports Button and ButtonProps), so other components can reuse or extend the props.
  • A design system wraps native elements (ComponentProps<'button'>) and uses unions for variants. Storybook usually has one story per variant.
  • ESLint's react/jsx-key catches missing keys. react-hooks/rules-of-hooks catches hooks in the wrong place (next topic).
  • Tests with React Testing Library render the component and query it the way a user would (by role and label), which only works if your components render accessible markup.

The exercises

  1. What React renders: renderToString for a tiny element tree, including the 0 && trap and text escaping.
  2. Avatar props: required and optional props, literal unions and defaults.
  3. Controlled or uncontrolled: props that exclude each other with ?: never, and both input modes.
  4. Keys keep state: match children by key and type, and see why index keys move state around.
  5. A typed data table: a generic table whose column formatters get the right field type.
  6. mergeProps: combine props objects from several hooks, chaining event handlers, with an intersection type.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app