Skip to content

Instantly share code, notes, and snippets.

@EmNudge
Created May 26, 2024 22:38
Show Gist options
  • Save EmNudge/7092b70635c6067c8759f55e75d1c9f3 to your computer and use it in GitHub Desktop.
Save EmNudge/7092b70635c6067c8759f55e75d1c9f3 to your computer and use it in GitHub Desktop.
React Global State Demo
import { useState } from 'react';
type GlobalState<T> = { value: T };
const setStateMap = new Map<GlobalState<any>, Set<Function>>();
export function useGlobalState<T>(stateObj: GlobalState<T>) {
const setStateFuncs = setStateMap.get(stateObj) ?? new Set();
setStateMap.set(stateObj, setStateFuncs);
const [_, setState] = useState(Symbol()); // refresher
setStateFuncs.add(setState);
const setGlobalState = (newVal: T) => {
stateObj.value = newVal;
// refresh all listening component
for (const setStateFunc of setStateFuncs) {
setStateFunc(Symbol());
}
};
return [stateObj.value, setGlobalState] as const;
}
export const globalCount: GlobalState<number> = { value: 0 };
export const globalName: GlobalState<string> = { value: 'John' };
export const globalAge: GlobalState<number> = { value: 30 };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment