Sub topic 7
State versus props: what changes over time
This chapter assumes you can write a function component, read JSX, and use arrays and objects in JavaScript. You should also have the static version of the product table from the previous chapters, where every component renders only from props. Here you learn how to tell props from state, and how to decide which data in the product table belongs in which group.
Two kinds of data
React components work with two kinds of data: props and state. Both are plain JavaScript values, and both affect what a component renders. They differ in who owns them and whether they change.
- Props are values a parent passes to a child. The child reads them and does not modify them. Think of props as the arguments of a function.
- State is a value a component remembers between renders. The component owns it, and it changes in response to events such as typing or clicking.
In the product table, ProductRow receives a product prop. It can show product.name, but it cannot decide that the name should be something else. If the name needs to change, the parent has to pass a different value in the next render.
function ProductRow({ product }) {
// product is a prop: read it, never assign to it.
return (
<tr>
<td>{product.name}</td>
<td>{product.price}</td>
</tr>
);
}A prop that looks fixed from the child's point of view can still change over time. The parent may re-render with a new value, and the child then receives it. The child never changes the prop itself. Whoever owns the value changes it.
Props are a snapshot for one render
Each render of a component receives one set of props, and that set does not change during that render. React calls your function, you return JSX, and the props you read are fixed for that call. When something changes, React calls the function again with new props.
This is why mutating props is a bug and not a style problem. The following component compiles but breaks the model.
function ProductRow({ product }) {
// Wrong: this edits an object that belongs to the parent.
product.name = product.name.toUpperCase();
return (
<tr>
<td>{product.name}</td>
<td>{product.price}</td>
</tr>
);
}The object came from the PRODUCTS array, so every component that holds a reference to it sees the edit. React also has no way to know that anything changed, so it does not schedule a new render. If you need a different display value, compute it into a new variable and leave the prop alone.
function ProductRow({ product }) {
const displayName = product.name.toUpperCase();
return (
<tr>
<td>{displayName}</td>
<td>{product.price}</td>
</tr>
);
}State is memory that triggers renders
A normal local variable inside a component is recreated on every render, so it cannot remember anything. State solves two problems at once. It keeps a value between renders, and it tells React to render again when the value changes.
You create state with the useState hook. It returns the current value and a setter function.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Calling setCount does not edit count in place. It asks React to render the component again with the new value. During that new render, useState returns the updated number. The count you read inside one render stays the same for that whole render, just like props.
The following diagram shows that cycle.
Comparing props and state
The two kinds of data are easy to confuse when you start, because both appear as plain variables in your component. The table lists the practical differences.
| Question | Props | State |
|---|---|---|
| Who owns it? | The parent that passes it | The component that declares it |
| Can the component change it? | No, it is read-only | Yes, through the setter |
| What triggers a re-render? | The parent rendering with new values | Calling the setter with a new value |
| How does it get there? | JSX attributes: `<ProductRow product={p} />` | `useState(initialValue)` |
| Typical use | Configuration and data from above | Data that changes because of user input or time |
One value can play both roles in different components. In the finished product table, FilterableProductTable owns filterText as state. It passes filterText to ProductTable as a prop. From the point of view of ProductTable, the value is read-only. Only the owner can change it.
Applying the distinction to the mockup
Now return to the mockup. It has a search box, a checkbox, and a table of products. To decide which data is state, go through each piece of data and ask what kind of data it is. The product data looks like this:
const PRODUCTS = [
{ category: 'Fruits', price: '$1', stocked: true, name: 'Apple' },
{ category: 'Fruits', price: '$1', stocked: true, name: 'Dragonfruit' },
{ category: 'Fruits', price: '$2', stocked: false, name: 'Passionfruit' },
{ category: 'Vegetables', price: '$2', stocked: true, name: 'Spinach' },
{ category: 'Vegetables', price: '$4', stocked: false, name: 'Pumpkin' },
{ category: 'Vegetables', price: '$1', stocked: true, name: 'Peas' }
];The data in the app falls into these groups:
- The original list of products. It is passed in as a prop, so it is not state.
- The text the user typed in the search box. It starts empty, changes over time, and cannot be computed from anything else, so it looks like state.
- The value of the checkbox. It also changes over time and cannot be computed, so it looks like state.
- The filtered list of products. It can be computed from the original list, the search text, and the checkbox value, so it is not state.
That grouping is a first pass. The next chapter turns it into a precise test, but you can already see the pattern. Data that changes and cannot be derived is a candidate for state. Data that comes from a parent, or can be computed from other data, is not.
Three questions to ask about each value
A short checklist helps when a value is not obvious. Ask these questions about each piece of data, in order.
- Does it stay unchanged over time? If so, it is not state. Constants and fixed configuration can be props or plain variables.
- Is it passed in from a parent via props? If so, it is not state in this component. The parent may own it as state, but this component only reads it.
- Can you compute it from existing props or state? If so, it is not state. Calculate it during rendering.
If a value survives all three questions, it is state. In the product table, only the search text and the checkbox value survive.
Common mistakes
Several mistakes come up again and again when people first separate props from state.
Copying a prop into state
A frequent pattern is to initialize state from a prop.
import { useState } from 'react';
function ProductRow({ product }) {
// Risky: name is copied once and never follows the prop again.
const [name, setName] = useState(product.name);
return <td>{name}</td>;
}useState uses its argument only on the first render. If the parent later passes a different product, this component keeps showing the old name. You now have two sources of truth that can disagree. Read product.name directly instead. Copying a prop into state is only reasonable when you want the prop to act as an initial value and you intend to ignore later changes. In that case, name the prop initialName so the intent is clear.
Storing derived values
Storing the filtered list as state looks natural, because it is what the user sees. It creates a synchronization problem. Every time the search text changes you must remember to update the list, and any place you forget leaves the screen out of date. Compute the list during render from the sources of truth. The chapter on derived data shows this in full.
Changing state by assigning to it
State must be replaced through the setter. Assigning to the variable does nothing visible, because React does not know the value changed.
import { useState } from 'react';
function Broken() {
let [text, setText] = useState('');
function handleClick() {
text = 'changed'; // React is never told, so nothing re-renders.
}
return <button onClick={handleClick}>{text || 'Click me'}</button>;
}The same rule applies to objects and arrays held in state. Create a new object or array and pass it to the setter. Do not edit the existing one in place.
import { useState } from 'react';
function Cart() {
const [items, setItems] = useState(['Apple']);
function addPeas() {
// New array, so React sees a different value.
setItems([...items, 'Peas']);
}
return (
<div>
<button onClick={addPeas}>Add peas</button>
<p>{items.join(', ')}</p>
</div>
);
}Too much state in one place
If every value becomes state, components get hard to follow. Each extra piece of state is one more value that can fall out of step with the others. The aim is the smallest set of state that fully describes the UI. The next chapter develops that idea as the minimal representation of state.
Why the distinction pays off
Separating props from state gives you a predictable UI. For any render, the output depends on two inputs: the props the parent passed and the state the component holds. If you know both, you know what the screen shows. That makes bugs easier to find, because you can ask which input was wrong.
It also tells you where to make a change. If a value is wrong, find the component that owns it. For a prop, that is a parent. For state, it is the component that calls useState, or the setter's callers. The product table follows this rule. The search text lives in one place, and everything that depends on it reads it from there.
Edge cases to keep in mind
- A prop can be a function. Callback props are still props, because the child only calls them and does not replace them. The chapter on inverse data flow uses this to send changes upward.
- A prop that is an object or array is read-only in the same way. Do not change its fields, even though JavaScript allows it.
- State is private to each component instance. Two
Countercomponents on the same page keep separate counts. - A state value is a snapshot within one render. If a handler calls
setCount(count + 1)twice, both calls use the samecount, and the result is a single increment. Use the updater form,setCount((c) => c + 1), when the new value depends on the previous one.
import { useState } from 'react';
function DoubleClick() {
const [count, setCount] = useState(0);
function addTwo() {
setCount((c) => c + 1);
setCount((c) => c + 1);
}
return <button onClick={addTwo}>Count: {count}</button>;
}Summary
Props flow in from a parent and are read-only. State is memory owned by a component, and changing it through the setter causes a new render. To classify any value, ask whether it changes, whether a parent supplies it, and whether you can compute it from something else. In the product table, the product list is a prop, the search text and checkbox value are state, and the filtered rows are derived.
Exercise
In the product table, a developer adds const [visibleProducts, setVisibleProducts] = useState(products) and calls setVisibleProducts inside the search box's change handler to hold the filtered list. Using the three questions from this chapter, explain why visibleProducts should not be state, and say what to do instead.
Show answer
The filtered list changes over time and is not passed in directly, but it can be computed from the products prop, the search text, and the checkbox value. Because it passes the third question (it can be computed from existing props or state), it is not state. Storing it also copies a prop into state, so the list can fall out of step when products changes or when a handler forgets to update it. Instead, keep only the search text and the checkbox value as state, and build the filtered rows during render inside ProductTable by skipping products that do not match.
Exercise
A component calls setCount(count + 1) three times in one click handler, starting with count equal to 0. What does count equal after the next render, and how would you change the code to reach 3?
Show answer
It equals 1. All three calls read the same snapshot value of count from the current render (0), so each one asks for 1. To reach 3, use the updater form for each call: setCount((c) => c + 1). React then applies the updates in order, each using the result of the previous one.