Sub topic 8
Step 3: Find the minimal but complete state
This chapter assumes you can write a function component, pass props, and call useState. It also assumes you have the static version of the product table from the previous step. That version renders everything from props and holds no state, so nothing on screen can change yet.
The goal of this step is to decide which pieces of data must be state. The rule is to keep state minimal but complete. State should be the smallest set of values from which the whole UI can be computed. Everything else is derived during render.
Why minimal state matters
Every piece of state is a value you must keep consistent with the rest. If you store the same fact in two places, an update to one can leave the other stale. That bug is hard to see because both values look plausible on their own.
A useful way to think about it is the DRY principle ("don't repeat yourself") applied to data. Find the one source of truth for each fact, and compute the rest from it.
The three questions
For each piece of data in the app, ask these questions in order. If the answer to any of them is yes, the data is not state.
- Does it stay unchanged over time? If so, it is not state.
- Is it passed in from a parent via props? If so, it is not state.
- Can you compute it from existing state or props? If so, it is not state, even though it feels like it should be.
What is left after these questions is probably state.
Applying the questions to the product table
Here is the data model from the mockup.
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 app has these pieces of data:
- The original list of products.
- The search text the user has typed.
- The value of the checkbox.
- The filtered list of products.
Work through each one.
| Data | Changes over time? | Passed as props? | Computable from other data? | State? |
|---|---|---|---|---|
| Original product list | No | Yes, from the parent | Not applicable | No |
| Search text | Yes | No | No | Yes |
| Checkbox value | Yes | No | No | Yes |
| Filtered product list | Yes | No | Yes, from the list, search text, and checkbox | No |
The product list is passed in as a prop, so it is not state. The search text starts empty and changes as the user types. Nothing else holds it, and you cannot compute it from other data, so it is state. The checkbox follows the same reasoning. The filtered list changes, but you can always compute it from the other three values. It is derived data, so it is not state.
The result is two pieces of state: the search text and whether the checkbox is checked.
Declaring the state
Once you know what the state is, give each value its own useState call with a sensible initial value. The initial values describe the UI before the user does anything: an empty search box and an unchecked checkbox.
import { useState } from 'react';
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
// ...
}You have not decided yet which component should own this state. The next step covers that. For now, the point is only to name the values and pick their types. A string and a boolean are enough to describe every possible view of the table.
Common mistake: storing derived data
A tempting design is to keep the visible rows in state as well.
import { useState } from 'react';
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
// Avoid: this duplicates information that already exists.
const [visibleProducts, setVisibleProducts] = useState(products);
// ...
}This code needs an extra step on every change. When the user types, you must call setFilterText and also recompute and call setVisibleProducts. If you forget one call, the text box and the table disagree. If the products prop changes later, visibleProducts still holds the old list.
The next chapter shows the better approach: compute the rows during render from products, filterText, and inStockOnly. Then there is nothing to keep in sync.
Other things that are not state
Beyond the filtered list, a few other values often get stored by mistake.
- Counts and totals. A "3 items shown" label is the length of the filtered list. Compute it.
- Copies of props. Writing
useState(props.products)copies the prop once. Later changes to the prop are ignored. Use the prop directly unless you really want a snapshot. - Formatting. Lowercased search text, trimmed text, or a price formatted with a currency symbol can all be computed where you use them.
- Values that never trigger a re-render. If a value is not shown on screen, it may not belong in state at all. This chapter does not cover those cases, but be aware that state is for data that changes what the user sees.
Choosing the shape of each value
Minimal also applies to the shape of the data. Both of these values are as small as they can be.
filterTextis a string. You could store an object such as{ text: '' }, but it adds nothing.inStockOnlyis a boolean. You could store the strings'all'and'in-stock', but two states fit a boolean.
If you later add a third option, such as "out of stock only", a boolean no longer fits. At that point you would change it to a string or a small set of named values. Start with the simplest type that describes the current design, and change it when the design changes.
Complete as well as minimal
"Minimal" can be taken too far. State must also be complete. It must hold enough information to rebuild every screen the user can reach. Ask a test question: if I saved only the state and reloaded the page, could I restore exactly what the user saw?
For the product table, the answer is yes. The search text and the checkbox value, combined with the product list from props, determine every row. Nothing else on the screen needs to be remembered.
Consider what would break completeness. If the mockup also let the user sort by price, you would need a sort direction in state. Without it, the UI could not show the user's choice. Adding the sort direction is not a violation of minimalism. It is new information that cannot be derived from anything else.
Edge cases to check
Before moving on, test your state design against a few situations.
- Empty search text. The initial value
''should match every product, because every string includes the empty string. That is why''works as a "no filter" value, with no special case. - Case. The user types
applewhile the product name isApple. The comparison must lower-case both sides. This is a rendering concern, so the state keeps exactly what the user typed. - Nothing matches. The table renders no rows. The state is still valid, and no extra state such as
hasResultsis needed. You can derive it from the row count if you want a message. - The checkbox and the text together. Both filters apply at the same time. Because the two values are independent, there is no combined state to manage.
Notice that none of these cases required new state. When a new requirement can be met by computing from existing state, that is a sign the design is minimal.
Summary of the decision
| Question | If yes | Example from the table |
|---|---|---|
| Is it unchanged over time? | Not state | Category names in the data |
| Is it passed via props? | Not state | The `products` array |
| Can you compute it? | Not state | The filtered rows |
| None of the above? | State | `filterText`, `inStockOnly` |
Exercise
The product table gets a new label that says "Showing N products", where N is the number of rows currently visible. Should N be stored in state? Explain, using the three questions.
Show answer
No. The count changes over time and is not passed in via props, but it can be computed from existing data: it is the length of the filtered product list, which itself comes from products, filterText, and inStockOnly. Because it can be computed, it fails the third question and is not state. Storing it would create a second value that could drift from the real number of rows.
Exercise
A teammate writes const [products, setProducts] = useState(props.products) inside FilterableProductTable and never calls setProducts. Which question does this violate, and what goes wrong if the parent later passes a different array?
Show answer
It violates the second question: the products arrive via props, so they are not state. Because useState uses its initial value only on the first render, the component keeps showing the original array and ignores the new prop. The fix is to remove the state and use props.products directly.
Exercise
The mockup is extended so the user can click a column header to sort by price, ascending or descending. List the new state, if any, and say what you would derive.
Show answer
Add one piece of state for the sort direction, for example sortDirection set to 'asc' or 'desc', because the user's choice cannot be computed from anything else. The sorted order of the rows is derived: compute it during render from the filtered products and sortDirection, and do not store the sorted array in state.