React components, JSX, props and state
A React application is a tree of components: functions that take inputs and return a description of the UI. This page covers the four ideas everything else in React builds on: components written in JSX, props as a component’s inputs, state as its memory, and rendering lists and conditional content. The running example is the order screen of OrdersPortal, an invented back-office app.
The samples target React 19.3 (released September 2026). Each one was bundled with esbuild and run in Node.js 22: static components are rendered with react-dom/server and the printed HTML is shown; interactive ones are rendered into a jsdom document with react-dom/client and driven with act() from a short test driver shown at the end of the sample. In a real app the same components live in .jsx or .tsx files built by Vite or a framework.
Topics on this page
Section titled “Topics on this page”| Topic | Use it to |
|---|---|
| Components and JSX | Describe UI as functions that return markup-like JSX. |
| Props and composition | Pass data into components and build layouts from smaller pieces. |
| State | Remember values between renders and update the UI when they change. |
| Lists and conditional rendering | Render collections with keys, empty states and optional content. |
Components and JSX
Section titled “Components and JSX”A component is a JavaScript function whose name starts with a capital letter and that returns JSX. JSX looks like HTML but compiles to function calls (jsx('h3', { children: ... }) with the automatic runtime) that produce plain objects describing the UI tree; React compares that description with the previous one and updates only the DOM that changed. Because it is JavaScript, you embed any expression in curly braces, and attributes use JavaScript names: className instead of class, htmlFor instead of for, and camelCase event handlers such as onClick.
A component must be pure during rendering: given the same props and state it returns the same JSX and does not change anything outside itself (no network calls, no writes to global variables). That rule is what lets React render components in any order, pause and resume rendering, and, in development with StrictMode, call them twice to surface accidental side effects. Side effects belong in event handlers or effects, covered in Hooks, effects and context.
function StatusBadge({ status }) { const tone = status === 'shipped' ? 'success' : status === 'cancelled' ? 'danger' : 'neutral'; return <span className={`badge badge-${tone}`}>{status}</span>;}
function OrderCard({ order, currency = 'EUR' }) { const total = order.lines.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0); return ( <article className="order-card" aria-labelledby={`order-${order.id}`}> <h3 id={`order-${order.id}`}>Order {order.id}</h3> <StatusBadge status={order.status} /> <p>{order.lines.length} lines, {total.toFixed(2)} {currency}</p> </article> );}
// Driverimport { renderToStaticMarkup } from 'react-dom/server';const order = { id: 1001, status: 'shipped', lines: [{ unitPrice: 19.99, quantity: 2 }, { unitPrice: 5.5, quantity: 4 }] };console.log(renderToStaticMarkup(<OrderCard order={order} />));Output:
<article class="order-card" aria-labelledby="order-1001"><h3 id="order-1001">Order 1001</h3><span class="badge badge-success">shipped</span><p>2 lines, 61.98 EUR</p></article>Note that total is calculated during render rather than stored anywhere: values that can be derived from props should be computed, not copied into state.
Pitfalls:
- Lower-case component names.
<orderCard />is treated as an unknown HTML tag; component names must start with a capital letter. - Returning several siblings. A component returns one node; wrap siblings in a fragment (
<>...</>) instead of an extradiv. - Side effects in the function body. Fetching or mutating during render runs on every render, and twice in development
StrictMode.
Props and composition
Section titled “Props and composition”Props are the arguments of a component: an object of named values passed from the parent, read through destructuring (function OrderCard({ order, currency = 'EUR' })). They flow one way, from parent to child, and are read-only: a child never changes its props; it asks the parent to change by calling a function prop such as onChange. This one-way data flow is what makes a React screen predictable: to know why something renders, follow the props up the tree.
Any JSX can be a prop, and the content between a component’s tags arrives as the special children prop. That makes composition React’s main reuse tool: generic layout components (panels, dialogs, page shells) accept children or named slots such as actions, and specific components fill them in. Prefer this to configuration flags (showHeader, headerVariant, …) that grow without limit. Since React 19, ref is also an ordinary prop for function components, so forwardRef is no longer needed.
function Panel({ title, actions, children }) { return ( <section className="panel"> <header> <h2>{title}</h2> {actions} </header> <div className="panel-body">{children}</div> </section> );}
function CustomerPanel({ customer }) { return ( <Panel title="Customer" actions={<a href={`/customers/${customer.id}`}>Open</a>}> <p>{customer.name}</p> <p>{customer.email}</p> </Panel> );}
// Driverimport { renderToStaticMarkup } from 'react-dom/server';console.log(renderToStaticMarkup( <CustomerPanel customer={{ id: 'C-7', name: 'Ada Lopez', email: 'ada@example.test' }} />));Output:
<section class="panel"><header><h2>Customer</h2><a href="/customers/C-7">Open</a></header><div class="panel-body"><p>Ada Lopez</p><p>ada@example.test</p></div></section>Pitfalls:
- Mutating props (
props.order.status = 'paid') changes the parent’s data behind React’s back; the UI will not update reliably. - Prop drilling through many layers. Passing a value through five components that do not use it is a sign to use composition (pass the rendered child instead) or context.
- Spreading everything (
<Input {...props} />) hides the component’s real API and can pass unknown attributes to the DOM.
State is data a component remembers between renders, declared with useState. It returns the current value and a setter; calling the setter schedules a re-render of that component and its children with the new value. Inside one render, the state value is a snapshot: after setQuantity(quantity + 1) the variable quantity still holds the old value until the next render. When the new value depends on the old one and several updates may queue up, pass an updater function: setQuantity((q) => q + 1).
Treat state as immutable: to change an object or array, create a new one (setOrder({ ...order, status: 'paid' }), setLines(lines.filter(...))). React compares state with Object.is, so mutating in place and calling the setter with the same reference does not re-render. Keep state as close as possible to the components that use it, and lift it to the closest common parent only when siblings need to share it. Store the minimum: anything you can derive from props or other state (totals, filtered lists, validity) should be computed during render. When the updates become a set of named transitions, useReducer keeps them in one pure function.
import { useState } from 'react';
function QuantityPicker({ initial = 1, max = 10, onChange }) { const [quantity, setQuantity] = useState(initial);
function change(delta) { const next = Math.min(max, Math.max(1, quantity + delta)); setQuantity(next); onChange?.(next); }
return ( <div className="quantity"> <button onClick={() => change(-1)} disabled={quantity === 1}>-</button> <output>{quantity}</output> <button onClick={() => change(+1)} disabled={quantity === max}>+</button> </div> );}
// Driver: render into jsdom and click the buttons.import { act } from 'react';import { createRoot } from 'react-dom/client';const root = createRoot(document.getElementById('root'));await act(() => root.render(<QuantityPicker initial={2} max={3} onChange={(q) => console.log('onChange', q)} />));const [minus, plus] = document.querySelectorAll('button');const show = () => console.log(`quantity ${document.querySelector('output').textContent}, plus disabled: ${plus.disabled}`);show();await act(() => plus.click()); show();await act(() => plus.click()); show(); // disabled button: no click eventawait act(() => minus.click()); show();Output:
quantity 2, plus disabled: falseonChange 3quantity 3, plus disabled: truequantity 3, plus disabled: trueonChange 2quantity 2, plus disabled: falseThe component owns quantity and reports changes to its parent through onChange, which is the usual way to combine local state with one-way data flow.
Pitfalls:
- Reading state right after setting it. The variable keeps the old snapshot until the next render; compute
nextfirst, as above. - Copying props into state (
useState(props.order)) freezes the initial value; later prop changes are ignored. Derive instead, or reset with akey. - Duplicated state. Storing both
linesandlineCountinvites them to drift apart; keep one and derive the other.
Lists and conditional rendering
Section titled “Lists and conditional rendering”To render a collection, map the array to JSX and give each item a key that is stable and unique among its siblings, usually the database ID. React uses keys to match items between renders: with stable keys, inserting, removing or reordering keeps each row’s DOM and state with the right item. Array indexes are only safe for lists that never reorder, filter or insert.
Conditional UI is plain JavaScript: an early return for whole alternative states such as loading, error or empty; the ternary operator (a ? b : c) to choose between two pieces; and && to render something or nothing. null, undefined, true and false render nothing, but the number 0 renders as text, so write count > 0 && ... rather than count && ....
function OrderList({ orders, showCancelled }) { const visible = showCancelled ? orders : orders.filter((o) => o.status !== 'cancelled');
if (visible.length === 0) { return <p className="empty">No orders match this view.</p>; }
return ( <ul> {visible.map((order) => ( <li key={order.id}> Order {order.id}: {order.status} {order.priority && <strong> (priority)</strong>} </li> ))} </ul> );}
// Driverimport { renderToStaticMarkup } from 'react-dom/server';const orders = [ { id: 1001, status: 'shipped', priority: false }, { id: 1002, status: 'open', priority: true }, { id: 1003, status: 'cancelled', priority: false },];console.log(renderToStaticMarkup(<OrderList orders={orders} showCancelled={false} />));console.log(renderToStaticMarkup(<OrderList orders={[orders[2]]} showCancelled={false} />));Output:
<ul><li>Order 1001: shipped</li><li>Order 1002: open<strong> (priority)</strong></li></ul><p class="empty">No orders match this view.</p>Pitfalls:
- Index or random keys.
key={Math.random()}remounts every row on every render; index keys mix up input state when rows are reordered. 0 &&rendering a stray zero. Convert to a boolean with a comparison.- Nested ternaries. Past two levels, extract a component or use early returns.
Choosing between them
Section titled “Choosing between them”| Question | Answer |
|---|---|
| Does the parent decide the value? | Prop. |
| Does the component change it over time in response to the user? | State, in the lowest component that needs it. |
| Can it be calculated from props or other state? | Neither: compute it during render. |
| Do two siblings need it? | Lift state to their common parent and pass props down. |
| Do many distant components need it? | Context, or a dedicated store; see Hooks, effects and context. |
Interview questions
Section titled “Interview questions”What is the difference between props and state? Props are inputs owned by the parent and read-only in the child; state is owned by the component and changed only through its setter. A change to either re-renders the component. The same value should not be both.
Why does React need keys in lists? Keys identify items across renders so React can match old and new elements. Without stable keys, React matches by position, so removing the first row can make the second row inherit the first row’s DOM and local state.
Why does setCount(count + 1) called three times in one handler only add one?
count is the snapshot from the current render, so all three calls set the same value. setCount((c) => c + 1) queues three updater functions that each receive the latest pending value.
What does “components must be pure” mean in practice?
Rendering only calculates JSX from props, state and context. No network requests, timers, DOM writes or mutation of outside variables during render; those go in event handlers or effects. Purity enables concurrent rendering, StrictMode checks and memoization.
Senior scenario: a reusable DataTable has grown 25 boolean props and every new screen adds another. How would you redesign it?
Move from configuration to composition: expose building blocks (Table, Table.Header, Table.Row, column render functions or children) so screens assemble what they need. Keep the stateful behavior (sorting, selection, pagination) in a custom hook that the composed parts share, and keep the old API as a thin wrapper during migration so existing screens keep working.
Related pages
Section titled “Related pages”- Hooks, effects and context for effects, custom hooks and shared state.
- Forms and routing for inputs, form actions and React Router.
- Performance for re-render costs, memoization and the React Compiler.
- What is React? and the React overview.