Created
May 26, 2024 22:38
-
-
Save EmNudge/7092b70635c6067c8759f55e75d1c9f3 to your computer and use it in GitHub Desktop.
React Global State Demo
This file contains 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 { 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