Interface state
Which tab is open, whether a panel is collapsed: state your interface owns is held in cells, each with a value and a setter.
State private to a component
Section titled “State private to a component”useState takes an initial value and returns the value and its setter:
const [n, setN] = useState(0);<layer x={100} y={0} w={92} h={22} onClick={() => { setN(n + 1); }}>A useState(0) is per instance: a component drawn twice has two cells.
State shared between components
Section titled “State shared between components”Declare the cell once at the top level of a file, and every component that reads it shares it:
const openTab = sessionState(0);…const ShopTabs = (): Component => { const [tab, setTab] = useState(openTab);…const ShopContents = (): Component => { const [tab] = useState(openTab);Export the declaration to share it across files. A sessionState lasts
until the player logs out.
State that survives a restart
Section titled “State that survives a restart”persistedState saves a value on the player’s device:
const roofRemoval = persistedState(1, 'docs.settings.roofs');The second argument is a key. You can rename the variable freely, but changing the key declares a new setting and orphans every saved value under the old one.
Choosing between the three
Section titled “Choosing between the three”useState(0) | sessionState | persistedState | |
|---|---|---|---|
| Declared | at the call site | at the top of a file | at the top of a file |
| Shared | no, one per instance | yes | yes |
| Holds | a whole number | a number or a string | a number or a string |
| Lasts | while the component exists | until logout | across restarts, on that device |
Start with useState(0). Move to sessionState when a second component needs
the value, and to persistedState when the player would miss it tomorrow.
What a cell holds
Section titled “What a cell holds”A private cell holds a whole number; a boolean is 0 and 1. A string needs a top-level declaration:
const lastChoice = sessionState('');const [chosen, setChosen] = useState(lastChoice);Compare a string by its length, or use it in a template.
Setting state
Section titled “Setting state”A setter can be called from a handler, a function a handler calls, or another component:
const restoreDefaults = (): void => { const [, setRoofs] = useState(roofRemoval); const [, setShiftDrop] = useState(shiftClickDrop); … setRoofs(1); setShiftDrop(0);A handler’s reads are the values when it runs. If it derives several writes from one value, read it once at the top and use the local.