Skip to main content
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

const [value, setValue] = useState(initial)

Parameters

initial
any
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:
value
any
The current state value for this render.
setValue(next)
function
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 to setValue. The functional form is safer in async scenarios because it always operates on the latest state rather than a captured snapshot.
// direct value
setCount(5)

// functional updater (safe for async scenarios)
setCount(prev => prev + 1)

Example: Counter

const Counter = defineComponent({
  name: 'Counter',
  props: {},
  render() {
    const [count, setCount] = useState(0)
    return createElement('div', {},
      createElement('p', {}, `Count: ${count}`),
      createElement('button', { onclick: () => setCount(c => c + 1) }, '+'),
      createElement('button', { onclick: () => setCount(c => c - 1) }, '-'),
    )
  },
})

Multiple state values

You can call useState multiple times in a single render() function — each call manages its own independent piece of state.
const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [active, setActive] = useState(false)
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.