UNPKG

1.08 kBTypeScriptView Raw
1import React from "react"
2import { shallowEqual } from "./utils/utils"
3import { IValueMap } from "./types/IValueMap"
4
5export const MobXProviderContext = React.createContext<IValueMap>({})
6
7export interface ProviderProps extends IValueMap {
8 children: React.ReactNode
9}
10
11export function Provider(props: ProviderProps) {
12 const { children, ...stores } = props
13 const parentValue = React.useContext(MobXProviderContext)
14 const mutableProviderRef = React.useRef({ ...parentValue, ...stores })
15 const value = mutableProviderRef.current
16
17 if (__DEV__) {
18 const newValue = { ...value, ...stores } // spread in previous state for the context based stores
19 if (!shallowEqual(value, newValue)) {
20 throw new Error(
21 "MobX Provider: The set of provided stores has changed. See: https://github.com/mobxjs/mobx-react#the-set-of-provided-stores-has-changed-error."
22 )
23 }
24 }
25
26 return <MobXProviderContext.Provider value={value}>{children}</MobXProviderContext.Provider>
27}
28
29Provider.displayName = "MobXProvider"