Skip to main content

useState

Manage component state with reactive updates.

Import​

import { useState } from '@bedrock-core/ui';

Signature​

function useState<T>(initial: T | (() => T)): [T, (value: T | ((prev: T) => T)) => void]

Parameters​

ParameterTypeDescription
initialT | (() => 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:

  1. Current state value (T) - The current value of the state
  2. State setter function ((value: T | ((prev: T) => T)) => void) - Function to update the state. Can accept a new value directly or a function that receives the previous state and returns the new state

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']);

const addTodo = (): void => {
setTodos([...todos, `Task ${todos.length + 1}`]);
};

const removeLast = (): void => {
setTodos(todos.slice(0, -1));
};

return (
<Panel padding={10} gap={4}>
{todos.map((todo, index) => (
<Text key={index}>{`${index + 1}. ${todo}`}</Text>
))}
<Panel flexDirection={'row'} gap={8}>
<Button flex={1} onPress={addTodo}>
<Text>{'Add Todo'}</Text>
</Button>
<Button flex={1} onPress={removeLast} enabled={todos.length > 0}>
<Text>{'Remove Last'}</Text>
</Button>
</Panel>
</Panel>
);
}