Skip to content

Instantly share code, notes, and snippets.

@ChronSyn
Last active November 5, 2021 22:00
Show Gist options
  • Save ChronSyn/c1353fc63f058b8966583df70c539439 to your computer and use it in GitHub Desktop.
Save ChronSyn/c1353fc63f058b8966583df70c539439 to your computer and use it in GitHub Desktop.
MobX - useStores hook (Context)
import React from "react";
import { TouchableOpacity, Text } from "react-native";
import { observer } from "mobx";
import { useStores } from "../stores/StoresProvider";
const ExampleComponent: React.FC = () => {
const { UIStore } = useStores();
return (
<TouchableOpacity
onPress={() => UIStore.setUITheme(UIStore.UITheme === "dark" ? "light" : "dark")}
>
<Text>
Change theme
</Text>
</TouchableOpacity>
)
}
export default observer(ExampleComponent);
import React, { createContext, useContext } from "react";
import { singleton as UIStore } from "./UI.store";
export const StoresContext = createContext({
UIStore,
});
export const useStores = () => useContext(StoresContext);
import React, { useContext } from "react";
import { observable, action } from "mobx";
class UIStore {
@observable UITheme: "light" | "dark" = "dark";
@action setUITheme = (newState: "light" | "dark" = "dark") => {
this.UITheme = newState;
};
}
export const singleton = new UIStore();
const StoreContext = React.createContext<UIStore>(singleton);
export const StoreProvider = StoreContext.Provider;
export const useStore = () => useContext(StoreContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment