Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active October 29, 2019 20:38
Show Gist options
  • Select an option

  • Save itsMapleLeaf/33b665b594ec5c6c564ca8b46cbbff87 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/33b665b594ec5c6c564ca8b46cbbff87 to your computer and use it in GitHub Desktop.
root store hook example
// in RootStore.ts
export class RootStore {
userStore = new UserStore()
chatStore = new ChatStore()
appNavigationStore = new AppNavigationStore()
}
export const RootStoreContext = React.createContext<RootStore>()
export function useRootStore() {
const store = React.useContext(RootStoreContext)
if (!store) {
throw new Error(
"useRootStore() can only be used inside the RootStoreContext provider",
)
}
return store
}
// in index
ReactDOM.render(
<RootStoreContext.Provider value={new RootStore()}>
<App />
</RootStoreContext.Provider>,
document.getElementById("root"),
)
// in components
function UserProfile({ userId }: { userId: string }) {
const { userStore } = useRootStore()
const user = userStore.getUser(userId)
return (
<main>
<h1>{user.name}</h1>
<p>{user.bio}</p>
</main>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment