Prerequisites
- !Comfortable writing JavaScript functions, arrays and object literals
- !Basic HTML structure: elements, attributes and events
What You'll Learn
- 1Explain what React does during a render and why render functions must stay pure
- 2Move data between parent and child components with props and callback props
- 3Attach state to a component and predict exactly when it re-renders
- 4Render collections safely by giving every item a stable key
The render cycle in plain language
A React interface is a tree of components, and each component is a function: hand it some props, get back a description of what should be on screen. Rendering does not mean painting pixels. It means React calls your function, collects the JSX it returned, and compares that description with the version currently committed to the DOM. Only the differences are applied.
Two consequences follow from that definition, and they explain most beginner confusion. First, render functions must be pure: the same props in means the same JSX out, with no network calls, no writes to the DOM, and no mutation of module-level variables. Second, a render happens because state or props changed, not because a timer fired or because you want the view to refresh. When a setter runs, React schedules a re-render for that component and for any children that will receive new props. Work you perform during render runs again on every one of those passes, which is why heavy calculations either belong outside the component or behind memoization.
What JSX actually compiles into
JSX is a shorthand for creating plain JavaScript objects. Every element becomes a call that returns a descriptor, and the whole tree is just nested data your runtime can diff cheaply.
const view = (
<section className="card">
<h2>Order summary</h2>
<Total amount={42} />
</section>
);
// roughly what the compiler emits
const viewAgain = React.createElement(
'section',
{ className: 'card' },
React.createElement('h2', null, 'Order summary'),
React.createElement(Total, { amount: 42 })
);
The capitalisation rule falls out of this transformation. A tag written in lowercase becomes a string, so React looks up a host element such as div or button. A tag starting with an uppercase letter stays a variable reference, so it must be a component you imported or defined. Attributes are copied into a props object, and nested elements arrive as children. Because the tree is data, you can build parts of it in loops, store it in variables, and decide with ordinary conditionals before returning. Early returns and small helper variables are therefore idiomatic in React, not a style preference.
Props travel down, events travel up
Props are a component's inputs and they are read-only. A child may read what it receives, but rewriting a prop object or array in place silently corrupts the parent's data and produces a bug that only shows up later, when something unrelated re-renders. Treat props as immutable snapshots for the lifetime of that render.
Data flows one way, down. User intent flows the other way, up, through callback props. The naming convention is consistent across the ecosystem: an event prop is called what it does, such as onSelect or onDelete, and the parent passes a function that knows what to change.
function TodoItem({ todo, onToggle, onRemove }) {
return (
<li className={todo.done ? 'todo done' : 'todo'}>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.text}
</label>
<button type="button" onClick={() => onRemove(todo.id)}>
Delete
</button>
</li>
);
}
Notice what the child does not know: the shape of the list, the order of items, or where todos live. It reports an id and lets the owner decide. That single rule keeps components reusable and makes them trivial to test in isolation.
State, and the update that follows
State is a component's private memory that survives re-renders. Calling a setter with a new value schedules another render; React then recomputes the JSX and patches the DOM. Values are compared with Object.is, so passing the same number, string or reference again is a no-op, while passing a freshly built object or array always counts as a change even if its contents are identical.
function QuantityPicker({ initial = 1, onQuantityChange }) {
const [quantity, setQuantity] = useState(initial);
const changeBy = (delta) => {
setQuantity((current) => {
const next = Math.min(20, Math.max(1, current + delta));
return next;
});
};
useEffect(() => {
onQuantityChange(quantity);
}, [quantity, onQuantityChange]);
return (
<div className="picker">
<button type="button" onClick={() => changeBy(-1)}>ā</button>
<span aria-live="polite">{quantity}</span>
<button type="button" onClick={() => changeBy(1)}>+</button>
</div>
);
}
The functional form of the updater, where the previous value is passed into a function, is the safe default whenever the next value depends on the previous one. React batches updates that happen in the same event, so two setters in one click produce a single render with both changes applied.
Where each piece of data belongs
Most architecture decisions in React are really decisions about ownership. A good default is to keep data as close to the component that reads it as possible, then lift it only when a sibling genuinely needs the same value.
| Kind of data | Best home | Why it belongs there |
|---|---|---|
| Form field values | The form component, or a form library | Nothing else reads them, and they change on every keystroke |
| Filter text for a list | The component that owns the list | The filter and the filtered output must update together |
| Logged-in user | A provider or store near the root | Many distant components need it and it changes rarely |
| Theme and locale | Context provider | Static-ish values read by the whole tree |
| Server cache | A query library | Reusable, shareable, and invalidated by mutation |
| Derived values (totals, sorted arrays) | Compute during render | Storing them invites stale duplicates |
A useful test: if two components need the same value, lift it to their closest common ancestor. If only one component needs it, leave it where it is, even if that component is fairly high in the tree.
Composing components around shared state
A real screen is a small hierarchy, and the shape of that hierarchy decides where code goes. The component that owns the collection owns the array; the components that render individual rows receive slices of it plus the callbacks they need. Nothing reaches sideways into a sibling, and nothing reaches upward except through the function it was handed.
function CartPage() {
const [items, setItems] = useState(seedItems);
const remove = (id) => setItems((list) => list.filter((i) => i.id !== id));
const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
return (
<main>
<CartList items={items} onRemove={remove} />
<CartSummary total={total} count={items.length} />
<button type="button" disabled={!items.length} onClick={() => setItems([])}>
Empty cart
</button>
</main>
);
}
The total is derived rather than stored, so it can never drift out of sync with the list. That pattern, compute what you can and store only what the user actually changes, keeps the update path short and makes bugs easier to locate.
Symptoms of a component that is doing too much
You do not need a profiler to notice the early warnings. A component that receives a dozen props, mixes fetching with formatting with markup, and re-renders on every keystroke of an unrelated input is a maintenance problem before it becomes a performance problem. Watch for three signals: props that are only forwarded untouched through two or more layers, state that is written by one component but read by another that is not a child, and event handlers recreated on every render that feed memoized children, which defeats the memoization entirely.
The fix is usually structural rather than clever. Extract presentational pieces that take data and callbacks as props. Move shared state up only as far as it must go. Replace a growing list of optional props with a single configuration object, or with a small custom hook that owns the logic. When a component reaches the point where you cannot describe its job in one sentence, split it: the description is the contract each new piece should honour.
Common Mistakes
Mutating a prop object or array inside the child so the update shows up
Fix: Treat props as read-only and let the owner replace them with a new object built from the old one
Using an array index as the key of a list that can be reordered or filtered
Fix: Use a stable id from your data source, or restructure so each item has a durable identity
Fetching data during render by calling a service directly in the component body
Fix: Run the request inside an effect or a data-loading library so it does not repeat on every render
Passing a new object literal or inline arrow function to a memoized child on every render
Fix: Wrap the object in useMemo and the handler in useCallback, or hoist both out of the render path
Best Practices
- Keep render functions pure so React can re-run them safely at any time
- Name callback props after the action they perform, such as onSave or onRemove
- Prefer one-way data flow: derive display values during render instead of storing copies
- Split components when they mix unrelated concerns, not when they exceed an arbitrary line count
- Use early returns for loading and empty states instead of deeply nested conditional markup
Key Takeaways
- A render is a pure function call that returns a description, and React applies only the differences
- JSX becomes nested function calls: lowercase tags are host elements, uppercase tags are your components
- Props are read-only inputs flowing down; callbacks carry user intent back up
- State setters schedule renders, and batched setters produce a single combined update
- Stable keys are what let React keep component state attached to the right item across updates