State and Data Flow
useState basics
Props flow down from parent to child as read-only inputs, whereas state is data owned and updated by a component over time. Calling useState(initialValue) returns the current state value and a setter function that schedules a re-render. When the next state depends on the previous state—such as incrementing a counter or toggling a flag—pass an updater function (prev => ...) rather than reading the closed-over variable directly, because React batches multiple updates within the same event handler:
import { useState } from "react";
function QuantityStepper({ min = 1, max = 10 }) {
const [quantity, setQuantity] = useState(min);
function increment() {
// Functional updater guarantees we read the latest queued value, even in batched updates
setQuantity(prev => Math.min(max, prev + 1));
}
function decrement() {
setQuantity(prev => Math.max(min, prev - 1));
}
return (
<div className="d-flex align-items-center gap-2">
<button type="button" onClick={decrement} disabled={quantity <= min}>-</button>
<span aria-live="polite">{quantity}</span>
<button type="button" onClick={increment} disabled={quantity >= max}>+</button>
</div>
);
}
For objects and arrays, always replace the reference with a new copy (using spread syntax or array methods like .map() and .filter()) instead of mutating in place. React compares state references with Object.is; mutating the existing object leaves the reference unchanged and skips the re-render.
Lifting state up
When two sibling components need to stay synchronized—for example, a search input and a filtered results table—neither sibling should own a private copy of the filter text. Instead, move ("lift") that state to their nearest common ancestor and pass the value and setter callback down via props. This preserves React's one-way data flow: state lives in one place, and changes propagate predictably downward:
function CatalogPage({ products }) {
const [query, setQuery] = useState("");
return (
<section>
<SearchBar value={query} onChange={setQuery} />
<ProductList products={products} query={query} />
</section>
);
}
Derived state
Any value that can be computed from existing props or state should be calculated directly during render instead of stored in its own useState call. Storing redundant copies forces you to synchronize them manually, which is a common source of stale totals or mismatched counts:
function CartSummary({ items }) {
// Derived directly from `items` on every render; no extra state or useEffect needed
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
return (
<p>
{itemCount} items — ${subtotal.toFixed(2)}
</p>
);
}
State smells
Recognizing structural anti-patterns early keeps component trees predictable as features grow:
- Multiple sources of truth: Copying a prop into
useState(props.initialName)and expecting it to stay updated when the parent changesprops.initialName. Either make the component fully controlled via props or key it to reset intentionally. - Premature global state: Placing transient UI state (such as whether a dropdown is open or a hover tooltip is active) into a global store creates unnecessary coupling and re-renders across unrelated routes.
- Contradictory boolean flags: Using separate
isLoading,isSuccess, andisErrorbooleans can produce impossible combinations (like loading and error both true). Prefer a single status union such as"idle" | "loading" | "ready" | "error".
Professional tips
Apply these practices to keep state transitions clear and debuggable:
- Colocate state as close as possible to the components that read it, and lift it only when siblings must coordinate.
- Use immutable updates for nested objects and arrays so React's change detection and memoization remain reliable.
- Switch from multiple
useStatecalls touseReducerwhen state updates involve complex branching or interdependent fields.
Practice
Implement a shopping cart component with per-item quantity steppers, item removal, and a summary panel that derives total item count and subtotal without duplicating state.