Global state management? #152
-
Hello again, Is there currently a way to implement a global state not bound to a certain component or a single file? I think it can be a bit complex with VanJS specifically because of its direct DOM manipulation approach, which makes updating the DOM at a global scale challenging - at least according to my time working with it/reading the docs -, but a possible solution is to use a custom prop attached to functional components which can be used to access and modify a state globally: export type Theme = "dark" | "light";
// `provide` function uses a key to inject the passed state to the component passed to the resulting function
const theme = van.state<Theme>("light");
const provideTheme: ProvideFunc<Theme> = provider("theme", theme);
export interface StatefulComponent<TProps = any, TStates extends Record<string, State> = Record<string, State>> {
(props: TProps): ChildDom;
state: TState
}
export const ThemeButton: StatefulComponent<any, { theme: State<Theme> }> = () => {
// retrieve the `state` property of the caller function using a key
// if the state isn't found, the function will look for it in the nearest caller function
// the function can also inherit the callers state type
const theme = getState("theme");
// render something based on the current theme, toggle the current theme with an event
return button({onclick: () => theme.val = theme.val === "dark" ? "light" : "dark",
style: () => `background: ${theme.val === "light" ? "white" : "black"}`}, "Toggle Theme");
}
// inject state to component
provideTheme(ThemeButton)
// use the stateful component like any regular functional component
van.add(document.body, ThemeButton()) This is just some sketching code, I would like to get some opinions on the problem and how it could be solved. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 20 replies
-
To be honest I'm not quite familiar with the React Context API. My understanding of context is a collection of states at the global scope with a set of ergonomic APIs to get and set their values. I think VanJS (which is a reactive UI framework) is largely orthogonal to global state management. I feel that it's quite easy to provide some simple implementation for a straight-forward approach (e.g.: via a global variable or something in the For the code you have shown, I think it's a reasonable approach. I've seen no problems with it. |
Beta Was this translation helpful? Give feedback.
-
I think |
Beta Was this translation helpful? Give feedback.
Good
So I say we close this Q&A
See you later 👋🏼