React fundamentals
In React, the UI is a function of state. You say what the screen should show for each state, and React updates the page. Once you know that a render is only a function call, that state updates are queued and must never mutate, and that keys keep each item's identity, you can spot most common React bugs before they happen.
Author: bezzad
Contents
The problem: a cart that does not match the page
In the old version of our online shop, every “Add to cart” button changed several parts of the page by hand:
- The number on the cart icon at the top of the page.
- The cart list at the side of the page.
- The total price under the list.
One day a developer added a “Remove” button and forgot to update the total price. Now the cart is empty, but the total still shows $49. When every change must fix several parts of the page by hand, sooner or later one is missed.
The main idea: the UI is a function of state
React turns this around. You do not change the page by hand. You only say: “For this data, the page must look like this.”
- Data that changes over time is called state. For example, the contents of the cart.
- Each component is a function that takes state and props and returns a description of the page.
- When state changes, React calls the function again and changes only the parts of the page that are different.
So the cart number, the cart list and the total price are all made from one state. None of them can fall behind the others.
Components and JSX
A component is a normal function whose name starts with a capital letter and that returns JSX. JSX looks like HTML, but it is really JavaScript. Anything inside curly braces is a JavaScript expression.
type Product = { id: string; name: string; price: number };
type ProductCardProps = {
product: Product;
onAdd: (productId: string) => void;
};
export function ProductCard({ product, onAdd }: ProductCardProps) {
return (
<article className="product-card">
<h3>{product.name}</h3>
<p>${product.price.toFixed(2)}</p>
<button onClick={() => onAdd(product.id)}>Add to cart</button>
</article>
);
}
- The className attribute is used instead of class, because class is a keyword in JavaScript.
- Events are written in camelCase, like onClick, and take a function, not a string.
- A component name must start with a capital letter. React treats lowercase names as HTML tags.
Read-only inputs: props
Props are the inputs of a component. The parent gives them, and the child only reads them.
- The ProductCard component must not change product. The data belongs to the parent.
- If the child needs to change something, the parent passes a function like onAdd. The child calls it, and the parent changes its own state.
- This rule keeps the data flow simple: data goes down, and events go up.
Component memory: state with the useState hook
The useState hook gives a component memory that stays between renders. It returns a value and a function to change it.
import { useState } from 'react';
export function QuantityPicker() {
const [quantity, setQuantity] = useState(1);
return (
<div>
<button onClick={() => setQuantity(quantity - 1)} disabled={quantity === 1}>-</button>
<span>{quantity}</span>
<button onClick={() => setQuantity(quantity + 1)}>+</button>
</div>
);
}
A normal variable cannot do this. A local variable is created again on every render, and changing it does not start a new render.
A render is a function call
In React, “render” means React calls your component function. There are three steps:
- Trigger: the page opens for the first time, or someone calls a set function.
- Render: React calls the component function and gets the new JSX. Nothing on the page has changed yet.
- Commit: React compares the new result with the old one and changes only the DOM nodes that are different. Then the browser paints the page.
The important result: each render has its own snapshot of state. A set function does not change the current variable. It only stores the new value for the next render:
function handleClick() {
setQuantity(quantity + 1);
console.log(quantity); // still the old value, for example 1
}
This is also why a component function must be pure: for the same inputs it returns the same JSX, and it changes nothing outside itself while rendering. Side effects belong in event handlers or effects.
State updates are queued
React collects all set calls of one event handler and renders only once after the handler ends. This is called batching. What does this code do?
function addThree() {
setQuantity(quantity + 1); // 1 + 1
setQuantity(quantity + 1); // 1 + 1 again
setQuantity(quantity + 1); // result: 2, not 4
}
- In this render, quantity is 1, and it stays 1 until the handler ends.
- All three lines say “make the next value 2”.
- The result is 2, not 4.
If the new value depends on the old one, pass an updater function. React runs these functions in order on the latest value:
function addThree() {
setQuantity(q => q + 1); // 1 -> 2
setQuantity(q => q + 1); // 2 -> 3
setQuantity(q => q + 1); // 3 -> 4
}
Never mutate state
Do not change (mutate) arrays and objects that are in state. Always make a new array or object.
type CartItem = { productId: string; quantity: number };
// Bad: the same array is changed, React may skip the render
cart.push({ productId, quantity: 1 });
setCart(cart);
// Good: a new array
setCart([...cart, { productId, quantity: 1 }]);
// Good: change one item with a new object for it
setCart(cart.map(item =>
item.productId === productId ? { ...item, quantity: item.quantity + 1 } : item,
));
// Good: remove one item
setCart(cart.filter(item => item.productId !== productId));
Why?
- React compares the old and new value with Object.is. It only checks whether it is the same object, not what is inside.
- After the push method, the array is the same array as before. React thinks nothing changed and may not render at all.
- Tools like memo and useMemo depend on the same comparison. Mutation breaks them too.
Watch out for methods that change an array in place: push, splice, sort and reverse. To sort, the toSorted method returns a new array.
Lifting state up
The number on the cart icon and the product list both need the cart. If each one has its own state, we are back to the problem at the start of this lesson. The fix: move the state to the closest common parent.
import { useState } from 'react';
export function ShopPage({ products }: { products: Product[] }) {
const [cart, setCart] = useState<CartItem[]>([]);
function handleAdd(productId: string) {
setCart(prev => {
const found = prev.some(item => item.productId === productId);
if (!found) return [...prev, { productId, quantity: 1 }];
return prev.map(item =>
item.productId === productId ? { ...item, quantity: item.quantity + 1 } : item,
);
});
}
// Derived value: computed during render, not stored in state
const itemCount = cart.reduce((sum, item) => sum + item.quantity, 0);
return (
<>
<CartBadge count={itemCount} />
<ProductList products={products} onAdd={handleAdd} />
</>
);
}
- One source of truth. The cart is only in ShopPage.
- Do not put derived values in state. The item count is computed from the cart. If you keep it in a separate state, you must always keep two states in sync.
- Lift only as high as needed. The text of a search box that only one component needs should stay there.
Keys in lists
When you render a list with the map method, each item needs a key attribute. With the key, React knows which item in the new render is the same item as in the last render.
function CartList({ cart }: { cart: CartItem[] }) {
// Use a stable id from the data, not the index
return (
<ul>
{cart.map(item => (
<CartRow key={item.productId} item={item} />
))}
</ul>
);
}
Why is the index dangerous as a key?
- Say each cart row has a text box for a “gift note”. The user writes “gift” on the first row (shoes).
- With the index as the key, the shoes row has key 0.
- The user removes the shoes. Now the hat is first in the list and gets key 0.
- React thinks row 0 is the same row as before and keeps its state, the text “gift”. The note is now next to the hat.
- The index is only safe when the list is never sorted, filtered, removed from or added to, and the items have no state.
- Do not make the key during render, for example with Math.random. A new key on every render means the item is created again every time, and state and focus are lost.
- Changing a key on purpose resets state. For example, with the product id as the key on the review form, the form is empty when you go to the next product.
Controlled and uncontrolled inputs
In a controlled input, the value is in state and the input tag only shows it:
import { useState } from 'react';
export function SearchBox() {
const [query, setQuery] = useState(''); // start with '', not undefined
return (
<input
type="search"
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search products"
/>
);
}
In an uncontrolled input, the browser itself keeps the value. You only give the first value with defaultValue, and you read it when the form is sent:
export function NewsletterForm() {
function subscribe(formData: FormData) {
console.log('subscribe', formData.get('email'));
}
return (
<form action={subscribe}>
<input name="email" type="email" defaultValue="" />
<button type="submit">Subscribe</button>
</form>
);
}
- Controlled is good when you need every key press: a live filter, instant validation, disabling a button.
- Uncontrolled is simpler and is enough for forms you only read when they are sent.
- Do not switch halfway. If value is undefined at first and later becomes a string, the input goes from uncontrolled to controlled, and React shows a warning. Start with an empty string.
Do not define a component inside another component
// Bad: NoteField is a new component type on every render
export function CheckoutPage() {
const [note, setNote] = useState('');
function NoteField() {
return <textarea value={note} onChange={e => setNote(e.target.value)} />;
}
return <NoteField />;
}
- Every time CheckoutPage renders, the NoteField function is created again. A new function means a new component type.
- React compares the type. A new type means it removes the old component (unmount) and creates a fresh one (mount).
- The result: on every key press, the textarea tag is created again and loses focus. Any state inside it is lost too.
The fix: define the component outside, and pass what it needs as props:
type NoteFieldProps = { value: string; onChange: (value: string) => void };
function NoteField({ value, onChange }: NoteFieldProps) {
return <textarea value={value} onChange={e => onChange(e.target.value)} />;
}
Composition with children
Instead of building components with many props for every case, put components inside each other. Anything between the opening and closing tag of a component arrives in a prop named children:
import type { ReactNode } from 'react';
function Panel({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="panel">
<h2>{title}</h2>
{children}
</section>
);
}
export function CartSidebar({ cart }: { cart: CartItem[] }) {
return (
<Panel title="Your cart">
<CartList cart={cart} />
</Panel>
);
}
The Panel component does not know what is inside it. That is why it can be reused for the cart, the filters and the order summary. Sometimes this pattern also avoids passing props through many layers (prop drilling).
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| The push method on a state array, then set with the same array | The page does not update, or memo breaks. | Make a new array: spread, map or filter. |
| Calling set with quantity + 1 twice | Only one is added. | An updater function that adds one to the previous value. |
| Reading state right after set | You see the old value. | Keep the new value in a variable. |
| The index as the key in a list that changes | State and input text stay next to the wrong item. | A stable id from the data. |
| A component defined inside another component | Focus and state are lost on every render. | Define the component outside. |
| A first value of undefined for value | A warning about switching from uncontrolled to controlled. | Start with an empty string. |
| Keeping a derived value in state | Two states that fall out of sync. | Compute it during render. |
| Changing props in the child | The parent’s data changes without it knowing. | The parent passes a function. |
Summary in 7 lines
- The UI is a function of state. You say what the page should look like, and React updates it.
- Each component is a pure function. Props are read-only, and state is the component’s memory.
- A render is a function call. The page changes only in the commit step, and only where something is different.
- Each render has its own snapshot of state. Set calls are queued and applied together. Use an updater function when the new value depends on the old one.
- Never mutate state. Make new arrays and objects.
- Lift shared state to the closest common parent, and compute derived values during render.
- Use a stable id as the key in lists, and never define a component inside another component.