createStore function creates a Zustand store that automatically syncs with the widget’s persistent state. Unlike useWidgetState, this provides a full Zustand store with actions and middleware support, making it ideal for complex state management scenarios.
Basic usage
Parameters
storeCreator
defaultState
- A value of type
State - A function that returns
State(lazy initialization)
window.openai.widgetState exists, it will take precedence over defaultState.
Returns
store.getState()- Get the current statestore.setState()- Update the statestore.subscribe()- Subscribe to state changesuseStore(selector)- React hook to access the store
Features
Automatic State Persistence
State changes are automatically persisted towindow.openai.setWidgetState. The state is serialized (functions are stripped) before persistence.
State Initialization Priority
The store initializes state in the following order:window.openai.widgetState(if available) - highest prioritydefaultStateparameter (if provided)- State returned by
storeCreator
Examples
Todo List with Actions
Comparison with useWidgetState
| Feature | createStore | useWidgetState |
|---|---|---|
| Type | Zustand store | React hook |
| Use Case | Complex state with actions | Simple state updates |
| Actions | Supported | Not supported |
| Middleware | Can be composed | Not supported |
| Selectors | Full Zustand selectors | Returns full state |
| Performance | Fine-grained subscriptions | Re-renders on any change |
| API | Zustand API | React useState-like API |
createStore when you need:
- Actions and methods on your state
- Complex state logic
- Fine-grained subscriptions
- Zustand middleware support
useWidgetState when you need:
- Simple state management
- React
useState-like API - Quick setup without Zustand knowledge