Last active
November 5, 2021 22:00
-
-
Save ChronSyn/c1353fc63f058b8966583df70c539439 to your computer and use it in GitHub Desktop.
MobX - useStores hook (Context)
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 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); |
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 React, { createContext, useContext } from "react"; | |
import { singleton as UIStore } from "./UI.store"; | |
export const StoresContext = createContext({ | |
UIStore, | |
}); | |
export const useStores = () => useContext(StoresContext); |
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 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