React AI Rules: Should Code Start With State?
In React, AI-generated code does not have to start with state: the right starting point is the component’s data flow, and state is needed only for values that can change and affect what the interface shows. If a prompt or coding rule says to “start with state,” treat it as a planning hint, not a React requirement; first identify the inputs, derived values, and user interactions.
What “start with state” means
The phrase can refer to two different things. It may mean planning a component by deciding what data it owns before writing its JSX. That is often useful. Or it may mean that every component should begin with a useState call. That is not a React rule and can make a simple component more complicated than necessary.
React components can render from props, local state, context, or a combination of these. A component with no changing data can simply return JSX. For example:
function Greeting({ name }) {
return <p>Hello, {name}</p>;
}
Here, name comes from a prop. The component does not own an interactive value, so adding state would be unnecessary. State becomes useful when something changes over time, such as text entered in a field, whether a menu is open, or which item a user selected.
How React state works
State is data a component retains between renders. With a function component, useState provides the current value and a setter:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(value => value + 1)}>
Count: {count}
</button>
);
}
The initial value is 0. When the user clicks, the setter schedules an update, and React renders the component with the new value. Calling the setter does not change the current variable in the middle of the existing render. The functional update form, value => value + 1, is particularly helpful when the next value depends on the previous one.
State is not the same as an ordinary local variable. A local variable is recreated when a component function runs, and changing it does not tell React to render again. Use state when a value must persist across renders and a change to it should update the UI.
Decide what belongs in state
Before asking an AI tool to write a component—or writing it yourself—list the values the interface needs. For each one, ask where it comes from and whether it changes independently.
- Props: Values supplied by a parent, such as a product name or a list of records. A child should generally use the value it receives rather than make a second local copy.
- State: Values changed by interaction or another event, such as a form’s current input, a selected tab, or a loading flag.
- Derived values: Results that can be calculated from props or state, such as a filtered list or an item count. Calculate these during rendering unless there is a specific reason not to.
- External or shared data: Values used across distant parts of an application may belong in a shared state solution or a data-fetching layer. The right choice depends on the application, not on a universal instruction to put everything in component state.
For example, a shopping list might keep the list of items and the search query as state. The visible matching items can be computed from those values. Storing the matching items separately as another state variable creates two sources of truth: after an update, one may change while the other remains stale.
A practical workflow for AI-generated React code
A useful prompt gives the tool the component’s behavior and constraints, rather than requiring state as the first line. Ask it to identify the data sources, keep state minimal, and explain any state it adds. Then review the result against the intended interaction.
- Describe the UI and behavior. Specify what the user sees, what actions are available, and what should change after each action.
- Identify ownership. Say which values arrive as props, which are editable locally, and which are shared with a parent or another part of the app.
- Request minimal state. Ask the tool not to store values that can be calculated from existing props or state.
- Check update logic. Confirm that event handlers use state setters, and use functional updates when an update depends on the previous value.
- Test behavior. Try initial, empty, and changed states. Check that the visible UI follows the data and that lists use stable keys when rendered from arrays.
A focused prompt could say: “Build a search component. The query starts empty and changes as the user types. Receive the item list as a prop, derive the filtered results during rendering, and explain why each state variable is needed.” This encourages sound design without prescribing an unnecessary structure.
Common mistakes and misconceptions
Putting every value in state: This adds synchronization work. If a value can be computed from existing data, compute it instead of maintaining a duplicate.
Copying props into state automatically: A prop can change when its parent renders. Copying it once into state may leave the child displaying an outdated value. Only make a local copy when the component intentionally needs an independent, editable version and has a clear update strategy.
Mutating state directly: Do not change an object or array in place and expect React to detect the change. Create a new object or array and pass it to the setter. For example, use setItems(items => [...items, newItem]) to add an item.
Using an effect for every calculation: An effect is not needed merely to keep a derived value in sync with state. Extra effects can create more renders and harder-to-follow logic. Effects are mainly for synchronizing with systems outside React, such as subscriptions or browser APIs.
Assuming AI output is correct because it compiles: Code can compile while having stale state, incorrect event behavior, or needless complexity. Review the data flow, test interactions, and follow the conventions of the project. AI-generated code is a draft, not an authoritative React rule.
Frequently Asked Questions
Should every React component use state?
No. Components that only display props or constant content do not need state. Add it when the component must retain changing data and show the result of that change.
Should I declare state before writing JSX?
You can plan state first, but React does not require it. Decide what data the component needs, then write the state and rendering that fit its behavior.
Can AI decide which values belong in React state?
AI can suggest a design, but you should verify it. Check whether each value changes independently, whether it is already a prop, and whether it can be derived from existing data.
Why does changing a variable not update the screen?
Changing an ordinary local variable does not schedule a React render. Use a state setter for component data that should persist between renders and affect the displayed UI.
Should filtered or calculated data be state?
Usually not. Calculate it from the source data and relevant state during rendering. Consider memoization only when measurement shows that the calculation is costly or referential stability is needed.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.