MCPcopy
hub / github.com/mobxjs/mobx / observer

Function observer

packages/mobx-react-lite/src/observer.ts:77–176  ·  view source on GitHub ↗
(
    baseComponent:
        | React.ForwardRefRenderFunction<TRef, P>
        | React.FunctionComponent<P>
        | React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>,
    // TODO remove in next major
    options?: IObserverOptions
)

Source from the content-addressed store, hash-verified

75
76// n.b. base case is not used for actual typings or exported in the typing files
77export function observer<P extends object, TRef = {}>(
78 baseComponent:
79 | React.ForwardRefRenderFunction<TRef, P>
80 | React.FunctionComponent<P>
81 | React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>,
82 // TODO remove in next major
83 options?: IObserverOptions
84) {
85 if (process.env.NODE_ENV !== "production" && warnObserverOptionsDeprecated && options) {
86 warnObserverOptionsDeprecated = false
87 console.warn(
88 `[mobx-react-lite] \`observer(fn, { forwardRef: true })\` is deprecated, use \`observer(React.forwardRef(fn))\``
89 )
90 }
91
92 if (ReactMemoSymbol && baseComponent["$$typeof"] === ReactMemoSymbol) {
93 throw new Error(
94 `[mobx-react-lite] You are trying to use \`observer\` on a function component wrapped in either another \`observer\` or \`React.memo\`. The observer already applies 'React.memo' for you.`
95 )
96 }
97
98 // The working of observer is explained step by step in this talk: https://www.youtube.com/watch?v=cPF4iBedoF0&feature=youtu.be&t=1307
99 if (isUsingStaticRendering()) {
100 return baseComponent
101 }
102
103 let useForwardRef = options?.forwardRef ?? false
104 let render = baseComponent
105
106 const baseComponentName = baseComponent.displayName || baseComponent.name
107
108 // If already wrapped with forwardRef, unwrap,
109 // so we can patch render and apply memo
110 if (ReactForwardRefSymbol && baseComponent["$$typeof"] === ReactForwardRefSymbol) {
111 useForwardRef = true
112 render = baseComponent["render"]
113 if (typeof render !== "function") {
114 throw new Error(
115 `[mobx-react-lite] \`render\` property of ForwardRef was not a function`
116 )
117 }
118 }
119
120 let observerComponent = (props: any, ref: React.Ref<TRef>) => {
121 return useObserver(() => render(props, ref), baseComponentName)
122 }
123
124 // Inherit original name and displayName, see #3438
125 ;(observerComponent as React.FunctionComponent).displayName = baseComponent.displayName
126
127 if (isFunctionNameConfigurable) {
128 Object.defineProperty(observerComponent, "name", {
129 value: baseComponent.name,
130 writable: true,
131 configurable: true
132 })
133 }
134

Calls 2

isUsingStaticRenderingFunction · 0.90
copyStaticPropertiesFunction · 0.70

Tested by 1

obsComponentFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…