create function creates a React Hook that contains your store’s state and actions. It returns a hook with API utilities attached, allowing you to access state in your React components.
Import
- TypeScript
- JavaScript
Type Signature
Parameters
A function that receives
set, get, and store as arguments and returns the initial state object with actions.The function signature is:set: Function to update the stateget: Function to get the current statestore: The store API object withsetState,getState,subscribe, etc.
Returns
A React Hook that can be called to access the store state. The hook has the following signature:The hook also has the following API utilities attached:
setState: Update the stategetState: Get the current state outside of ReactgetInitialState: Get the initial statesubscribe: Subscribe to state changes
Basic Usage
- TypeScript
- JavaScript
Using the Entire State
You can access the entire state object by calling the hook without a selector:Accessing State Outside React
UsegetState to read state outside of React components:
Subscribing to State Changes
Subscribe to state updates outside of React:Updating State
Theset function supports both partial updates and function updates:
By default,
set performs a shallow merge. Pass true as the second argument to replace the state entirely.Related
- createStore - Create a vanilla (non-React) store
- createWithEqualityFn - Create a store with custom equality function