Skip to main content

Asynchronous state

The root state can be set to a promise value, either as an initial value for hookstate/useHookstate or as a subsequent value via State.set method.

Checking if state is loading

While a promise is not resolved or rejected almost any operation will result in an exception. To check if underlying promise is resolved or rejected, use State.promised. To check if underlying promise is rejected, use State.error. For example:


Executing an action when state is loaded

It is also possible to access the underlying promise and add a value handling on the promise resolution:

const state = hookstate(new Promise(...));
state.promise.then(() => {})
const state = hookstate(none);
state.promise.then(() => {})
setTimeout(() => state.set(...), 1000)

Suspending rendering until asynchronous state is loaded

Suspend is a React 18 feature. Hookstate provides integration with it in 2 ways:

  • the suspend function
  • and the suspend option of the StateFragment component.

Both methods work with local, global and scoped states.


function MyComponent() {
let state = useHookstate(new Promise(...))
return suspend(state) ?? <p>State is loaded: {state.value}</p>