useState
Manage component state with reactive updates.
Import
import { useState } from '@bedrock-core/ui';
import type { Immutable, StateSlot, StateUpdate } from '@bedrock-core/ui';
Signature
function useState<T>(initial: T | (() => T)): StateSlot<T>
Parameters
| Parameter | Type | Description |
|---|---|---|
initial | T | (() => T) (generic) | The initial value for the state variable, or a function that returns the initial value (lazy initialization) |
Returns
An array with two elements:
- Current state value (
Immutable<T>) — A deeply read-only view of the state in TypeScript - State setter function (
(value: StateUpdate<T>) => void) — Accepts a replacement or an updater(previous: Immutable<T>) => T
The setter keeps the same identity across renders of a mounted component. Functional updates receive the current state when they run. Setters retained after unmount are ignored, including their updater functions. Replace object and array values rather than mutating them in place.
Usage
function Counter() {
const [count, setCount] = useState(0);
return (
<Panel padding={10} gap={8}>
<Text>{`Count: ${count}`}</Text>
<Button onPress={() => setCount(count + 1)}>
<Text>{'Increment'}</Text>
</Button>
</Panel>
);
}
Examples
Toggle
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<Button onPress={() => setIsOn(!isOn)}>
<Text>{isOn ? '§aON' : '§7OFF'}</Text>
</Button>
);
}
Object state
interface PlayerStats {
health: number;
mana: number;
level: number;
}
function StatsDisplay() {
const [stats, setStats] = useState<PlayerStats>({
health: 100,
mana: 50,
level: 1,
});
const heal = (): void => {
setStats({ ...stats, health: Math.min(stats.health + 10, 100) });
};
const levelUp = (): void => {
setStats({ ...stats, level: stats.level + 1 });
};
return (
<Panel padding={10} gap={8}>
<Text>{`Health: ${stats.health}`}</Text>
<Text>{`Mana: ${stats.mana}`}</Text>
<Text>{`Level: ${stats.level}`}</Text>
<Panel flexDirection={'row'} gap={8}>
<Button flex={1} onPress={heal}>
<Text>{'Heal (+10)'}</Text>
</Button>
<Button flex={1} onPress={levelUp}>
<Text>{'Level Up'}</Text>
</Button>
</Panel>
</Panel>
);
}
Array state
function TodoList() {
const [todos, setTodos] = useState<string[]>(['First task']);
return (
<Panel padding={10} gap={4}>
<List max={5} items={todos} row={todo => (
<Text width={160}>{todo ?? ''}</Text>
)} />
<Button enabled={todos.length < 5}
onPress={() => setTodos(current => [...current, `Task ${current.length + 1}`])}>
<Text>{'Add Todo'}</Text>
</Button>
<Button enabled={todos.length > 0} onPress={() => setTodos(current => current.slice(0, -1))}>
<Text>{'Remove Last'}</Text>
</Button>
</Panel>
);
}
List reserves a fixed row capacity so the compiled screen keeps the same shape as items are added or removed.