Skip to content

Instantly share code, notes, and snippets.

@KEIII
Created April 24, 2026 20:02
Show Gist options
  • Select an option

  • Save KEIII/fef6bba95c0013ea5cba3567be09ad6a to your computer and use it in GitHub Desktop.

Select an option

Save KEIII/fef6bba95c0013ea5cba3567be09ad6a to your computer and use it in GitHub Desktop.
Example of creating simple store with React hook useSyncExternalStore
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