Created
April 24, 2026 20:02
-
-
Save KEIII/fef6bba95c0013ea5cba3567be09ad6a to your computer and use it in GitHub Desktop.
Example of creating simple store with React hook useSyncExternalStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useSyncExternalStore } from "react"; | |
| type F = () => void; | |
| export interface SimpleStore<T> { | |
| setValue: (v: T | ((prev: T) => T)) => void; | |
| subscribe: (onStoreChange: F) => F; | |
| getSnapshot: () => T; | |
| getServerSnapshot: () => T; | |
| } | |
| export const fromUpdaterOrValue = <T>(updaterOrValue: T | ((value: T) => T)): ((prev: T) => T) => { | |
| return typeof updaterOrValue === "function" | |
| ? updaterOrValue as ((value: T) => T) | |
| : () => updaterOrValue; | |
| }; | |
| export const createSimpleStore = <T>(initialValue: T): SimpleStore<T> => { | |
| let currentValue = initialValue; | |
| const observers = new Set<F>(); | |
| return { | |
| setValue: (updaterOrValue: T | ((prev: T) => T)) => { | |
| const nextValue = fromUpdaterOrValue(updaterOrValue)(currentValue); | |
| if (nextValue !== currentValue) { | |
| currentValue = nextValue; | |
| for (const observer of observers) { | |
| observer(); | |
| } | |
| } | |
| }, | |
| subscribe: (onStoreChange: F) => { | |
| observers.add(onStoreChange); | |
| return () => observers.delete(onStoreChange); | |
| }, | |
| getSnapshot: () => currentValue, | |
| getServerSnapshot: () => initialValue, | |
| }; | |
| }; | |
| export const useSimpleStore = <T, U>( | |
| store: SimpleStore<T>, | |
| selector: (state: T) => U, | |
| ) => useSyncExternalStore( | |
| store.subscribe, | |
| () => selector(store.getSnapshot()), | |
| () => selector(store.getServerSnapshot()), | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment