Sub topic 3
Controlled Inputs and Well-Structured React State
Assume JavaScript functions, JSX, props, array methods, destructuring, and spread syntax. A controlled input is a form element whose value comes from React state. The onChange handler updates that state.
Controlled inputs and state shape
Keep related fields in one object when they change together. Create a new object instead of mutating the existing one.
import { useState } from 'react';
export default function Directory({ items }) {
const [form, setForm] = useState({ query: '', role: 'all' });
function updateField(event) {
setForm({ ...form, [event.target.name]: event.target.value });
}
const visible = items.filter(item =>
item.name.toLowerCase().includes(form.query.toLowerCase()) &&
(form.role === 'all' || item.role === form.role)
);
return (
<>
<input
name="query"
value={form.query}
onChange={updateField}
placeholder="Search"
/>
<select name="role" value={form.role} onChange={updateField}>
<option value="all">All roles</option>
<option value="admin">Admin</option>
</select>
<p>{visible.length} result(s)</p>
</>
);
}Store the smallest source data needed to render the interface. visible is a derived value, meaning React computes it from existing props and state during render. Storing both items and visible creates two sources of truth that can become inconsistent.
Lifting state up
When sibling components need the same data, move that state to their closest common parent. The parent passes the current value and event callbacks as props. This keeps one authoritative copy.
Lazy initialization and resetting state
Pass a function to useState when initial setup is expensive. React calls that function only when the state is initialized:
useState(() => JSON.parse(localStorage.getItem('cart') ?? '[]'))
State belongs to a component’s position in the rendered tree. Give a component a different key to make React discard its old state and mount it again. For example, <Profile key={userId} userId={userId} /> resets a profile draft when userId changes.
When `useReducer` fits better
Use useReducer when many related updates make useState handlers difficult to follow. A reducer is a function that receives current state and an action, then returns the next state. It works well for state transitions such as loading, success, failure, and reset.
Common pitfalls
- Do not copy props into state unless you deliberately need an independent draft.
- Use updater functions such as
setCount(c => c + 1)when the next value depends on the previous value. - Use stable keys from item identity, not array indexes when items can be inserted or removed.
- Do not store values that can be calculated during render.
Exercise
Why should a filtered list usually be derived during render instead of stored in state?
Show answer
Its source data and filter already determine it. Deriving it avoids duplicate state and prevents the two values from going out of sync.