react-svelte-stores
Truly Reactive Stores for React. Inspired by Svelte
npm i react-svelte-stores
Why?
-
I wanted a good set of primitives with which I could build custom state management solutions.
-
I wanted a "cleaner" API than React's Context.
-
Gateway drug to Svelte, or a way for people who already love Svelte to write Svelte-like code in React.
Recipes
FSM Audio Player
You can use react-svelte-stores to create a finite state machine component that can receive messages from other components. Let's implement a minimal audio player to demonstrate this pattern.
- The discriminated union of states represents the vertices of a state diagram.
- The switch cases in the reducer function represent the edges of a state diagram; the transitions between states.
- Side effects are handled in
useEffect
Player.tsx
;; // discriminated union of possible states.; // discriminated union of possible actions; ; ; ; ;
- Music applications commonly allow you to pause or play tracks from components other than the track player. We can do this by
importing
playerFSM
and callingplayerFSM.dispatch
! - Because we need to know whether the player is playing or paused, we subscribe to the store state. In order to prevent unnecessary rerenders when the time is updated (we only care about the player status, not the time), we use
useSelectedStoreState
, which takes a selector function as its second argument.
OtherComponent.tsx
;
This approach makes it (nearly?) impossible to reach impossible states, while making cross-component communication clean and easy. You can even dispatch actions without subscribing to the FSM store. This style of reducer function, which considers the previous state as well as the action, was inspired by this David K. Piano tweet
Persisted Service
API Reference
Hooks
useStoreState(store: IStore<T>): T
useSelectedStoreState(store: IStore<T>, selector: <T, R>(state: T) => R): R
- Compatible with reselect
Stores
writable(initialState: T): IWritableStore<T>
readable(initialState: T, setCallback?: ReadableSetCallback<T>): IReadableStore<T>
persisted(initialState: T, storeKey: string): IWritableStore<T>
persistedAsync(initialState: T, storeKey: string, AsyncStorage: AsyncStorageStatic): IWritableStore<T>
Custom stores must expose the subscribe function to be usable with hooks.