- Home
- Skills
- Flpbalada
- My Opencode Config
- React Use State
react-use-state_skill
136
GitHub Stars
1
Bundled Files
2 months ago
Catalog Refreshed
4 months ago
First Indexed
Readme & install
Copy the install command, review bundled files from the catalogue, and read any extended description pulled from the listing source.
Installation
Preview and clipboard use veilstrat where the catalogue uses aiagentskills.
npx veilstrat add skill flpbalada/my-opencode-config --skill react-use-state- SKILL.md5.6 KB
Overview
This skill guides correct and efficient use of React's useState hook. It explains when useState is the right choice, when to prefer alternatives, and common pitfalls that cause stale updates or ignored changes. Followable rules and patterns help keep state predictable and performant.
How this skill works
The skill inspects component state scenarios and recommends the appropriate approach: useState for simple local state, useReducer for complex transitions, useRef for mutable values that shouldn't trigger renders, and useMemo for expensive derived values. It highlights critical rules like immutability, updater functions for sequential changes, initializer functions for costly defaults, and the top-level hooks rule.
When to use it
- Local component values that trigger re-renders (form inputs, toggles, counters).
- Simple state transitions where you replace a value directly.
- When you need to persist a value across renders without external storage.
- Not for global/shared state or values derivable from props/state.
Best practices
- Never mutate state directly; always return new objects/arrays (spread, map, filter).
- Use the functional updater (setState(prev => next)) when new state depends on previous state.
- Provide an initializer function to avoid expensive work on every render (useState(() => init())).
- Call hooks only at the top level of components; never inside conditionals or loops.
- Compute derived values during render or with useMemo instead of storing redundant state.
Example use cases
- Form input values: const [name, setName] = useState('') and update onChange.
- UI toggles and modals: const [isOpen, setIsOpen] = useState(false).
- Local lists: setItems(items => [...items, newItem]) for adding without mutating.
- Sequential counters: setCount(c => c + 1) called multiple times to accumulate updates.
- Expensive default state: const [todos, setTodos] = useState(() => createTodos()).
FAQ
React compares references; mutating the same object keeps the reference unchanged. Create a new object/array and pass that to setState so React sees the change.
I called setState then logged the value and it was old. Is that a bug?
No. State updates are asynchronous snapshots. Use the updater function or read the new value from a computed variable you set before calling setState.