# State and handlers

> Components that remember, react to a press in your own code, and follow the player, a setting or your store; and how the same JSX renders once on the server.

Page: https://songstress.app/docs/develop/state/

In client code a component is **mounted**: Songstress keeps it while the person has its page, panel, status item or
overlay open, calls your function when they press, type or slide, and draws it again when its state changes. The
function runs in your extension's sandbox, beside the app, never in it: the page is drawn again at once, with no trip
to the server. Ask for `"songstress": "^0.1.12"`.

## A counter [#a-counter]

The `components` template starts with this page:

```tsx title="src/counter.tsx"
import { songstress } from 'songstress/client'
import { Button, confirmed, HStack, Section, Stack, Text, useStored } from 'songstress/ui'

function Counter() {
  const [count, setCount, loading] = useStored('count', 0)
  return (
    <Stack gap="medium">
      <Section title="Counted so far">
        <Text style="title">{loading ? '…' : count}</Text>
      </Section>
      <HStack gap="small">
        <Button title="Add one" icon="add" emphasis="primary" onPress={() => setCount((was) => was + 1)} />
        <Button
          title="Start again"
          disabled={count === 0}
          onPress={confirmed({ title: 'Start again from 0?', confirm: 'Start again', destructive: true }, () => setCount(0))}
        />
      </HStack>
    </Stack>
  )
}

songstress.ui.pages.register('counter', () => <Counter />)
```

```json title="songstress.json"
"engines": { "songstress": "^0.1.12" },
"entry": { "client": "dist/client.js" },
"permissions": { "storage": { "reason": "Keep the count until you start again." } },
"contributes": {
  "pages": [{ "id": "counter", "title": "Counter", "icon": "add", "render": "client", "sidebar": true }]
}
```

## Handlers [#handlers]

`onPress`, `onChange`, `onSubmit`, a tab's `onSelect`, a tree's `onExpand` and a menu option's `onSelect` take an
[action](/docs/develop/interface/#actions), or, in client code, a function. A function is called with the value the
person chose (a switch's `true` or `false`, a field's text, a slider's number) and may answer an action for the app
to carry out, a toast say. `confirmed(question, then)` asks first, and runs `then` on yes.

A function never leaves the sandbox: the tree the app gets names it by a number, which the app hands back with the
value. An event is handled in the order the person made it.

A press on something of yours is also what lets your code change what plays: `player.playSongs`, the queue's changes
and `ui.navigate` go right after one ([the press rule](/docs/develop/data/#the-player-asked)). A command your code
runs itself is no press, and a command a handler's answer runs rides what is left of the press before it.

## State [#state]

- `useState`, `useReducer`, `useRef`, `useMemo`, `useCallback` and `useEffect` (cleaned up when the person leaves)
  hold and change a component's state; `useAsync(load, deps)` waits on a promise for you (`data`, `error`,
  `loading`).
- `usePlayer()` follows the player. It needs `listening.read`, and the client hooks it listens on in `hooks.client`
  (`onPlay`, `onPause`, `onTrackChange`, `onSeek`, `onVolumeChange`, `onProgress`); `songstress check` warns of a
  `usePlayer` with none of them listed (`PLAYER_HOOKS_UNLISTED`).
- `useSetting(key)` follows a setting; `useStored(key, initial)` is a value in your store, the member's own (with
  `storage`): what you set shows at once, and is written.

A change renders the component again, and the new tree reaches the app at most 30 times a second, and only when it
differs. An app holds 16 mounts of one extension at most.

State lasts while its target is mounted. Keep what must outlast it with `useStored` (or `songstress.storage`): the
person leaving ends a mount, and so does the end of the extension's sandbox, which on Android can come from another
extension (the phone's web views share one renderer, so ending a runaway extension's ends them all, and every mount
starts again at its first state). A phone stops client code while the app is behind and starts it again when the app
comes to the front, so a page still open then starts again at its first state too: a count kept with `useState` is
back at its start, one kept with `useStored` is where the person left it.

A render that throws, or goes over the [caps](/docs/develop/interface/#what-a-tree-cant-do), leaves the last tree on
screen and says why in the extension's log.

## A status item that counts down [#a-status-item-that-counts-down]

A status item may be a component too: a function whose answer is the item (`StatusContent`: its `text`, `icon`,
`tooltip`, `action`...), mounted as a page is:

```tsx title="src/minutes.tsx"
import { songstress, type StatusContent } from 'songstress/client'
import { useEffect, useState } from 'songstress/ui'

function Minutes(): StatusContent {
  const [left, setLeft] = useState(30)
  useEffect(() => {
    const tick = setInterval(() => setLeft((was) => Math.max(0, was - 1)), 60_000)
    return () => clearInterval(tick)
  }, [])
  return { text: `${left} min`, icon: 'timer', action: { type: 'navigate', to: { page: 'timer' } } }
}

songstress.ui.status.register('timer', () => <Minutes />)
```

A status item that only changes when your code says so needs no renderer at all: see
[Status and context keys](/docs/develop/status-and-context/).

## On the server, once [#on-the-server-once]

A server renderer that answers an element renders it once, with its first values, and runs no effect: a server keeps
no state between two looks at a page. Its handlers are actions, and a function is refused (`not-available`). Start a
server file that draws JSX with this line, and the compiler refuses a function handler before the server does:

```tsx title="src/stats.tsx"
/** @jsxImportSource songstress/ui/server */
import { songstress } from 'songstress/server'
import { Section, Switch } from 'songstress/ui'

songstress.ui.pages.register('stats', () => (
  <Section title="Options">
    <Switch label="Count skips" value={false} onChange={{ type: 'invoke', command: 'set-skips' }} />
  </Section>
))
```

The command is run with the value the person chose as `input.value`.

## Test it [#test-it]

`songstress/testing` mounts a component as an app does. `host.mount(kind, id)` mounts what your entry registered,
and `mount(<Counter />)` an element of your own; then `press`, `change` and `submit` what the tree names, by its key,
its id, its label or its title. Each answers the action the app would carry out next. A JSX `key` names a part before
its title, so key two lists apart. `page.tree` is the reader's answer, `{ ok, tree }`: the screen itself is
`page.tree.tree`.

```tsx title="src/counter.test.tsx"
import { createMockHost } from 'songstress/testing'
import { expect, it, vi } from 'vitest'
import manifest from '../songstress.json'

it('adds one at each press, and keeps the count', async () => {
  const host = createMockHost({ manifest, side: 'client' })
  vi.resetModules()
  await import('./counter')

  const page = await host.mount('page', 'counter')
  await page.press('Add one')
  expect(JSON.stringify(page.tree)).toContain('"text":"1"')
  await page.unmount()
  host.remove()
})
```

More in [Test and debug](/docs/develop/testing/#mount-a-component).
