MCPcopy
hub / github.com/reduxjs/react-redux / useSelector

Function useSelector

src/hooks/useSelector.ts:138–254  ·  view source on GitHub ↗
(
    selector: (state: TState) => Selected,
    equalityFnOrOptions:
      | EqualityFn<NoInfer<Selected>>
      | UseSelectorOptions<NoInfer<Selected>> = {},
  )

Source from the content-addressed store, hash-verified

136 : createReduxContextHook(context)
137
138 const useSelector = <TState, Selected>(
139 selector: (state: TState) => Selected,
140 equalityFnOrOptions:
141 | EqualityFn<NoInfer<Selected>>
142 | UseSelectorOptions<NoInfer<Selected>> = {},
143 ): Selected => {
144 const { equalityFn = refEquality } =
145 typeof equalityFnOrOptions === 'function'
146 ? { equalityFn: equalityFnOrOptions }
147 : equalityFnOrOptions
148 if (process.env.NODE_ENV !== 'production') {
149 if (!selector) {
150 throw new Error(`You must pass a selector to useSelector`)
151 }
152 if (typeof selector !== 'function') {
153 throw new Error(`You must pass a function as a selector to useSelector`)
154 }
155 if (typeof equalityFn !== 'function') {
156 throw new Error(
157 `You must pass a function as an equality function to useSelector`,
158 )
159 }
160 }
161
162 const reduxContext = useReduxContext()
163
164 const { store, subscription, getServerState } = reduxContext
165
166 const firstRun = React.useRef(true)
167
168 const wrappedSelector = React.useCallback<typeof selector>(
169 {
170 [selector.name](state: TState) {
171 const selected = selector(state)
172 if (process.env.NODE_ENV !== 'production') {
173 const { devModeChecks = {} } =
174 typeof equalityFnOrOptions === 'function'
175 ? {}
176 : equalityFnOrOptions
177 const { identityFunctionCheck, stabilityCheck } = reduxContext
178 const {
179 identityFunctionCheck: finalIdentityFunctionCheck,
180 stabilityCheck: finalStabilityCheck,
181 } = {
182 stabilityCheck,
183 identityFunctionCheck,
184 ...devModeChecks,
185 }
186 if (
187 finalStabilityCheck === 'always' ||
188 (finalStabilityCheck === 'once' && firstRun.current)
189 ) {
190 const toCompare = selector(state)
191 if (!equalityFn(selected, toCompare)) {
192 let stack: string | undefined = undefined
193 try {
194 throw new Error()
195 } catch (e) {

Callers 9

GlobalCountButtonFunction · 0.85
hooks.test-d.tsxFile · 0.85
CompFunction · 0.85
Comp2Function · 0.85
AppFunction · 0.85
ChildFunction · 0.85
RenderSelectorFunction · 0.85
DisplayDefaultCountFunction · 0.85

Calls

no outgoing calls

Tested by 7

GlobalCountButtonFunction · 0.68
CompFunction · 0.68
Comp2Function · 0.68
AppFunction · 0.68
ChildFunction · 0.68
RenderSelectorFunction · 0.68
DisplayDefaultCountFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…