Skip to content

useSelector Hook

The create function also returns another hook, the useSelector hook.

In a lot of cases you only want to display a value or you want to compute a display value from the state. In those cases, you can use the useSelector hook, since it is bit more performant than the useAppState hook and only re-renders when the computed value changes.

tsx
import { create } from '@restate/core'

// We create our app state and a hook to access the state:
const { useAppState, useSelector } = create({
  state: {
    name: 'John',
    age: 32
  }
})

function Greeting() {
  const greeting = useSelector((s) =>
    s.age > 30 ? 'Good day Sir!' : `Hey there, ${s.name}!`
  )
  return <h1>{greeting}!</h1>
}

function AgeInput() {
  const [age, setAge] = useAppState((s) => s.age)
  return <input value={age} onChange={(e) => setAge(Number(e.target.value))} />
}

function Hint() {
  return (
    <>
      <hr />
      <div>
        Try to set the age below 30 and observe how the computed greeting is
        changing.
      </div>
    </>
  )
}

export function HelloUseSelector() {
  return (
    <div className="layout">
      <Greeting />
      <AgeInput />
      <Hint />
    </div>
  )
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

Use useSelector if you only want to display the value or compute a value from the state.


Full example on https://stackblitz.com/edit/hello-restate

Released under the MIT License.