useState lets you add reactive state to a Solar component. The value persists across re-renders, and updating it schedules a re-render automatically — you never need to manually trigger a refresh.
Signature
Parameters
The initial state value. You can pass any value directly, or pass a function
() => initialValue that Solar calls once on the first render to compute the initial value lazily.Returns
useState returns a two-element tuple:
The current state value for this render.
The updater function. Call it with a new value, or with a function
prev => newValue that receives the previous state and returns the next one.Functional updater
You can pass either a direct value or a function tosetValue. The functional form is safer in async scenarios because it always operates on the latest state rather than a captured snapshot.
Example: Counter
Multiple state values
You can calluseState multiple times in a single render() function — each call manages its own independent piece of state.
Always call
useState at the top level of your render() function. Never call it inside a condition, loop, or nested function — Solar tracks hooks by call order, and changing that order between renders will cause mismatches.Multiple
setState calls made within a single event handler are batched into one re-render. Your component re-renders once with all the updated values applied together.