@depup/react-redux 9.3.0-depup.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +32 -0
  3. package/changes.json +14 -0
  4. package/dist/cjs/index.js +6 -0
  5. package/dist/cjs/react-redux.development.cjs +1119 -0
  6. package/dist/cjs/react-redux.development.cjs.map +1 -0
  7. package/dist/cjs/react-redux.production.min.cjs +6 -0
  8. package/dist/cjs/react-redux.production.min.cjs.map +1 -0
  9. package/dist/react-redux.browser.mjs +6 -0
  10. package/dist/react-redux.browser.mjs.map +1 -0
  11. package/dist/react-redux.d.ts +587 -0
  12. package/dist/react-redux.legacy-esm.js +1105 -0
  13. package/dist/react-redux.legacy-esm.js.map +1 -0
  14. package/dist/react-redux.mjs +1071 -0
  15. package/dist/react-redux.mjs.map +1 -0
  16. package/dist/rsc.mjs +46 -0
  17. package/dist/rsc.mjs.map +1 -0
  18. package/package.json +124 -0
  19. package/src/components/Context.ts +50 -0
  20. package/src/components/Provider.tsx +105 -0
  21. package/src/components/connect.tsx +845 -0
  22. package/src/connect/invalidArgFactory.ts +14 -0
  23. package/src/connect/mapDispatchToProps.ts +25 -0
  24. package/src/connect/mapStateToProps.ts +14 -0
  25. package/src/connect/mergeProps.ts +78 -0
  26. package/src/connect/selectorFactory.ts +242 -0
  27. package/src/connect/verifySubselectors.ts +26 -0
  28. package/src/connect/wrapMapToProps.ts +110 -0
  29. package/src/exports.ts +51 -0
  30. package/src/hooks/useDispatch.ts +104 -0
  31. package/src/hooks/useReduxContext.ts +42 -0
  32. package/src/hooks/useSelector.ts +286 -0
  33. package/src/hooks/useStore.ts +123 -0
  34. package/src/index-rsc.ts +35 -0
  35. package/src/index.ts +1 -0
  36. package/src/types.ts +180 -0
  37. package/src/utils/Subscription.ts +183 -0
  38. package/src/utils/batch.ts +4 -0
  39. package/src/utils/bindActionCreators.ts +16 -0
  40. package/src/utils/hoistStatics.ts +139 -0
  41. package/src/utils/isPlainObject.ts +17 -0
  42. package/src/utils/react-is.ts +97 -0
  43. package/src/utils/react.ts +3 -0
  44. package/src/utils/shallowEqual.ts +36 -0
  45. package/src/utils/useIsomorphicLayoutEffect.ts +40 -0
  46. package/src/utils/useSyncExternalStore.ts +9 -0
  47. package/src/utils/verifyPlainObject.ts +14 -0
  48. package/src/utils/warning.ts +21 -0
@@ -0,0 +1,845 @@
1
+ /* eslint-disable valid-jsdoc, @typescript-eslint/no-unused-vars */
2
+ import type { ComponentType } from 'react'
3
+ import { React } from '../utils/react'
4
+ import { isValidElementType, isContextConsumer } from '../utils/react-is'
5
+
6
+ import type { Store } from 'redux'
7
+
8
+ import type {
9
+ ConnectedComponent,
10
+ InferableComponentEnhancer,
11
+ InferableComponentEnhancerWithProps,
12
+ ResolveThunks,
13
+ DispatchProp,
14
+ ConnectPropsMaybeWithoutContext,
15
+ } from '../types'
16
+
17
+ import type {
18
+ MapStateToPropsParam,
19
+ MapDispatchToPropsParam,
20
+ MergeProps,
21
+ MapDispatchToPropsNonObject,
22
+ SelectorFactoryOptions,
23
+ } from '../connect/selectorFactory'
24
+ import defaultSelectorFactory from '../connect/selectorFactory'
25
+ import { mapDispatchToPropsFactory } from '../connect/mapDispatchToProps'
26
+ import { mapStateToPropsFactory } from '../connect/mapStateToProps'
27
+ import { mergePropsFactory } from '../connect/mergeProps'
28
+
29
+ import type { Subscription } from '../utils/Subscription'
30
+ import { createSubscription } from '../utils/Subscription'
31
+ import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect'
32
+ import shallowEqual from '../utils/shallowEqual'
33
+ import hoistStatics from '../utils/hoistStatics'
34
+ import warning from '../utils/warning'
35
+
36
+ import type {
37
+ ReactReduxContextValue,
38
+ ReactReduxContextInstance,
39
+ } from './Context'
40
+ import { ReactReduxContext } from './Context'
41
+
42
+ // Define some constant arrays just to avoid re-creating these
43
+ const EMPTY_ARRAY: [unknown, number] = [null, 0]
44
+ const NO_SUBSCRIPTION_ARRAY = [null, null]
45
+
46
+ // Attempts to stringify whatever not-really-a-component value we were given
47
+ // for logging in an error message
48
+ const stringifyComponent = (Comp: unknown) => {
49
+ try {
50
+ return JSON.stringify(Comp)
51
+ } catch (err) {
52
+ return String(Comp)
53
+ }
54
+ }
55
+
56
+ type EffectFunc = (...args: any[]) => void | ReturnType<React.EffectCallback>
57
+
58
+ // This is "just" a `useLayoutEffect`, but with two modifications:
59
+ // - we need to fall back to `useEffect` in SSR to avoid annoying warnings
60
+ // - we extract this to a separate function to avoid closing over values
61
+ // and causing memory leaks
62
+ function useIsomorphicLayoutEffectWithArgs(
63
+ effectFunc: EffectFunc,
64
+ effectArgs: any[],
65
+ dependencies?: React.DependencyList,
66
+ ) {
67
+ useIsomorphicLayoutEffect(() => effectFunc(...effectArgs), dependencies)
68
+ }
69
+
70
+ // Effect callback, extracted: assign the latest props values to refs for later usage
71
+ function captureWrapperProps(
72
+ lastWrapperProps: React.MutableRefObject<unknown>,
73
+ lastChildProps: React.MutableRefObject<unknown>,
74
+ renderIsScheduled: React.MutableRefObject<boolean>,
75
+ wrapperProps: unknown,
76
+ // actualChildProps: unknown,
77
+ childPropsFromStoreUpdate: React.MutableRefObject<unknown>,
78
+ notifyNestedSubs: () => void,
79
+ ) {
80
+ // We want to capture the wrapper props and child props we used for later comparisons
81
+ lastWrapperProps.current = wrapperProps
82
+ renderIsScheduled.current = false
83
+
84
+ // If the render was from a store update, clear out that reference and cascade the subscriber update
85
+ if (childPropsFromStoreUpdate.current) {
86
+ childPropsFromStoreUpdate.current = null
87
+ notifyNestedSubs()
88
+ }
89
+ }
90
+
91
+ // Effect callback, extracted: subscribe to the Redux store or nearest connected ancestor,
92
+ // check for updates after dispatched actions, and trigger re-renders.
93
+ function subscribeUpdates(
94
+ shouldHandleStateChanges: boolean,
95
+ store: Store,
96
+ subscription: Subscription,
97
+ childPropsSelector: (state: unknown, props: unknown) => unknown,
98
+ lastWrapperProps: React.MutableRefObject<unknown>,
99
+ lastChildProps: React.MutableRefObject<unknown>,
100
+ renderIsScheduled: React.MutableRefObject<boolean>,
101
+ isMounted: React.MutableRefObject<boolean>,
102
+ childPropsFromStoreUpdate: React.MutableRefObject<unknown>,
103
+ notifyNestedSubs: () => void,
104
+ // forceComponentUpdateDispatch: React.Dispatch<any>,
105
+ additionalSubscribeListener: () => void,
106
+ ) {
107
+ // If we're not subscribed to the store, nothing to do here
108
+ if (!shouldHandleStateChanges) return () => {}
109
+
110
+ // Capture values for checking if and when this component unmounts
111
+ let didUnsubscribe = false
112
+ let lastThrownError: Error | null = null
113
+
114
+ // We'll run this callback every time a store subscription update propagates to this component
115
+ const checkForUpdates = () => {
116
+ if (didUnsubscribe || !isMounted.current) {
117
+ // Don't run stale listeners.
118
+ // Redux doesn't guarantee unsubscriptions happen until next dispatch.
119
+ return
120
+ }
121
+
122
+ // TODO We're currently calling getState ourselves here, rather than letting `uSES` do it
123
+ const latestStoreState = store.getState()
124
+
125
+ let newChildProps, error
126
+ try {
127
+ // Actually run the selector with the most recent store state and wrapper props
128
+ // to determine what the child props should be
129
+ newChildProps = childPropsSelector(
130
+ latestStoreState,
131
+ lastWrapperProps.current,
132
+ )
133
+ } catch (e) {
134
+ error = e
135
+ lastThrownError = e as Error | null
136
+ }
137
+
138
+ if (!error) {
139
+ lastThrownError = null
140
+ }
141
+
142
+ // If the child props haven't changed, nothing to do here - cascade the subscription update
143
+ if (newChildProps === lastChildProps.current) {
144
+ if (!renderIsScheduled.current) {
145
+ notifyNestedSubs()
146
+ }
147
+ } else {
148
+ // Save references to the new child props. Note that we track the "child props from store update"
149
+ // as a ref instead of a useState/useReducer because we need a way to determine if that value has
150
+ // been processed. If this went into useState/useReducer, we couldn't clear out the value without
151
+ // forcing another re-render, which we don't want.
152
+ lastChildProps.current = newChildProps
153
+ childPropsFromStoreUpdate.current = newChildProps
154
+ renderIsScheduled.current = true
155
+
156
+ // TODO This is hacky and not how `uSES` is meant to be used
157
+ // Trigger the React `useSyncExternalStore` subscriber
158
+ additionalSubscribeListener()
159
+ }
160
+ }
161
+
162
+ // Actually subscribe to the nearest connected ancestor (or store)
163
+ subscription.onStateChange = checkForUpdates
164
+ subscription.trySubscribe()
165
+
166
+ // Pull data from the store after first render in case the store has
167
+ // changed since we began.
168
+ checkForUpdates()
169
+
170
+ const unsubscribeWrapper = () => {
171
+ didUnsubscribe = true
172
+ subscription.tryUnsubscribe()
173
+ subscription.onStateChange = null
174
+
175
+ if (lastThrownError) {
176
+ // It's possible that we caught an error due to a bad mapState function, but the
177
+ // parent re-rendered without this component and we're about to unmount.
178
+ // This shouldn't happen as long as we do top-down subscriptions correctly, but
179
+ // if we ever do those wrong, this throw will surface the error in our tests.
180
+ // In that case, throw the error from here so it doesn't get lost.
181
+ throw lastThrownError
182
+ }
183
+ }
184
+
185
+ return unsubscribeWrapper
186
+ }
187
+
188
+ // Reducer initial state creation for our update reducer
189
+ const initStateUpdates = () => EMPTY_ARRAY
190
+
191
+ export interface ConnectProps {
192
+ /** A custom Context instance that the component can use to access the store from an alternate Provider using that same Context instance */
193
+ context?: ReactReduxContextInstance
194
+ /** A Redux store instance to be used for subscriptions instead of the store from a Provider */
195
+ store?: Store
196
+ }
197
+
198
+ interface InternalConnectProps extends ConnectProps {
199
+ reactReduxForwardedRef?: React.ForwardedRef<unknown>
200
+ }
201
+
202
+ function strictEqual(a: unknown, b: unknown) {
203
+ return a === b
204
+ }
205
+
206
+ /**
207
+ * Infers the type of props that a connector will inject into a component.
208
+ */
209
+ export type ConnectedProps<TConnector> =
210
+ TConnector extends InferableComponentEnhancerWithProps<
211
+ infer TInjectedProps,
212
+ any
213
+ >
214
+ ? unknown extends TInjectedProps
215
+ ? TConnector extends InferableComponentEnhancer<infer TInjectedProps>
216
+ ? TInjectedProps
217
+ : never
218
+ : TInjectedProps
219
+ : never
220
+
221
+ export interface ConnectOptions<
222
+ State = unknown,
223
+ TStateProps = {},
224
+ TOwnProps = {},
225
+ TMergedProps = {},
226
+ > {
227
+ forwardRef?: boolean
228
+ context?: typeof ReactReduxContext
229
+ areStatesEqual?: (
230
+ nextState: State,
231
+ prevState: State,
232
+ nextOwnProps: TOwnProps,
233
+ prevOwnProps: TOwnProps,
234
+ ) => boolean
235
+
236
+ areOwnPropsEqual?: (
237
+ nextOwnProps: TOwnProps,
238
+ prevOwnProps: TOwnProps,
239
+ ) => boolean
240
+
241
+ areStatePropsEqual?: (
242
+ nextStateProps: TStateProps,
243
+ prevStateProps: TStateProps,
244
+ ) => boolean
245
+ areMergedPropsEqual?: (
246
+ nextMergedProps: TMergedProps,
247
+ prevMergedProps: TMergedProps,
248
+ ) => boolean
249
+ }
250
+
251
+ /**
252
+
253
+ *
254
+ * Connects a React component to a Redux store.
255
+ *
256
+ * - Without arguments, just wraps the component, without changing the behavior / props
257
+ *
258
+ * - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior
259
+ * is to override ownProps (as stated in the docs), so what remains is everything that's
260
+ * not a state or dispatch prop
261
+ *
262
+ * - When 3rd param is passed, we don't know if ownProps propagate and whether they
263
+ * should be valid component props, because it depends on mergeProps implementation.
264
+ * As such, it is the user's responsibility to extend ownProps interface from state or
265
+ * dispatch props or both when applicable
266
+ *
267
+ * @param mapStateToProps
268
+ * @param mapDispatchToProps
269
+ * @param mergeProps
270
+ * @param options
271
+ */
272
+ export interface Connect<DefaultState = unknown> {
273
+ // tslint:disable:no-unnecessary-generics
274
+ (): InferableComponentEnhancer<DispatchProp>
275
+
276
+ /** mapState only */
277
+ <TStateProps = {}, no_dispatch = {}, TOwnProps = {}, State = DefaultState>(
278
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
279
+ ): InferableComponentEnhancerWithProps<TStateProps & DispatchProp, TOwnProps>
280
+
281
+ /** mapDispatch only (as a function) */
282
+ <no_state = {}, TDispatchProps = {}, TOwnProps = {}>(
283
+ mapStateToProps: null | undefined,
284
+ mapDispatchToProps: MapDispatchToPropsNonObject<TDispatchProps, TOwnProps>,
285
+ ): InferableComponentEnhancerWithProps<TDispatchProps, TOwnProps>
286
+
287
+ /** mapDispatch only (as an object) */
288
+ <no_state = {}, TDispatchProps = {}, TOwnProps = {}>(
289
+ mapStateToProps: null | undefined,
290
+ mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
291
+ ): InferableComponentEnhancerWithProps<
292
+ ResolveThunks<TDispatchProps>,
293
+ TOwnProps
294
+ >
295
+
296
+ /** mapState and mapDispatch (as a function)*/
297
+ <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = DefaultState>(
298
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
299
+ mapDispatchToProps: MapDispatchToPropsNonObject<TDispatchProps, TOwnProps>,
300
+ ): InferableComponentEnhancerWithProps<
301
+ TStateProps & TDispatchProps,
302
+ TOwnProps
303
+ >
304
+
305
+ /** mapState and mapDispatch (nullish) */
306
+ <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = DefaultState>(
307
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
308
+ mapDispatchToProps: null | undefined,
309
+ ): InferableComponentEnhancerWithProps<TStateProps, TOwnProps>
310
+
311
+ /** mapState and mapDispatch (as an object) */
312
+ <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = DefaultState>(
313
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
314
+ mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
315
+ ): InferableComponentEnhancerWithProps<
316
+ TStateProps & ResolveThunks<TDispatchProps>,
317
+ TOwnProps
318
+ >
319
+
320
+ /** mergeProps only */
321
+ <no_state = {}, no_dispatch = {}, TOwnProps = {}, TMergedProps = {}>(
322
+ mapStateToProps: null | undefined,
323
+ mapDispatchToProps: null | undefined,
324
+ mergeProps: MergeProps<undefined, DispatchProp, TOwnProps, TMergedProps>,
325
+ ): InferableComponentEnhancerWithProps<TMergedProps, TOwnProps>
326
+
327
+ /** mapState and mergeProps */
328
+ <
329
+ TStateProps = {},
330
+ no_dispatch = {},
331
+ TOwnProps = {},
332
+ TMergedProps = {},
333
+ State = DefaultState,
334
+ >(
335
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
336
+ mapDispatchToProps: null | undefined,
337
+ mergeProps: MergeProps<TStateProps, DispatchProp, TOwnProps, TMergedProps>,
338
+ ): InferableComponentEnhancerWithProps<TMergedProps, TOwnProps>
339
+
340
+ /** mapDispatch (as a object) and mergeProps */
341
+ <no_state = {}, TDispatchProps = {}, TOwnProps = {}, TMergedProps = {}>(
342
+ mapStateToProps: null | undefined,
343
+ mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
344
+ mergeProps: MergeProps<undefined, TDispatchProps, TOwnProps, TMergedProps>,
345
+ ): InferableComponentEnhancerWithProps<TMergedProps, TOwnProps>
346
+
347
+ /** mapState and options */
348
+ <TStateProps = {}, no_dispatch = {}, TOwnProps = {}, State = DefaultState>(
349
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
350
+ mapDispatchToProps: null | undefined,
351
+ mergeProps: null | undefined,
352
+ options: ConnectOptions<State, TStateProps, TOwnProps>,
353
+ ): InferableComponentEnhancerWithProps<DispatchProp & TStateProps, TOwnProps>
354
+
355
+ /** mapDispatch (as a function) and options */
356
+ <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}>(
357
+ mapStateToProps: null | undefined,
358
+ mapDispatchToProps: MapDispatchToPropsNonObject<TDispatchProps, TOwnProps>,
359
+ mergeProps: null | undefined,
360
+ options: ConnectOptions<{}, TStateProps, TOwnProps>,
361
+ ): InferableComponentEnhancerWithProps<TDispatchProps, TOwnProps>
362
+
363
+ /** mapDispatch (as an object) and options*/
364
+ <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}>(
365
+ mapStateToProps: null | undefined,
366
+ mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
367
+ mergeProps: null | undefined,
368
+ options: ConnectOptions<{}, TStateProps, TOwnProps>,
369
+ ): InferableComponentEnhancerWithProps<
370
+ ResolveThunks<TDispatchProps>,
371
+ TOwnProps
372
+ >
373
+
374
+ /** mapState, mapDispatch (as a function), and options */
375
+ <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = DefaultState>(
376
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
377
+ mapDispatchToProps: MapDispatchToPropsNonObject<TDispatchProps, TOwnProps>,
378
+ mergeProps: null | undefined,
379
+ options: ConnectOptions<State, TStateProps, TOwnProps>,
380
+ ): InferableComponentEnhancerWithProps<
381
+ TStateProps & TDispatchProps,
382
+ TOwnProps
383
+ >
384
+
385
+ /** mapState, mapDispatch (as an object), and options */
386
+ <TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = DefaultState>(
387
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
388
+ mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
389
+ mergeProps: null | undefined,
390
+ options: ConnectOptions<State, TStateProps, TOwnProps>,
391
+ ): InferableComponentEnhancerWithProps<
392
+ TStateProps & ResolveThunks<TDispatchProps>,
393
+ TOwnProps
394
+ >
395
+
396
+ /** mapState, mapDispatch, mergeProps, and options */
397
+ <
398
+ TStateProps = {},
399
+ TDispatchProps = {},
400
+ TOwnProps = {},
401
+ TMergedProps = {},
402
+ State = DefaultState,
403
+ >(
404
+ mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
405
+ mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
406
+ mergeProps: MergeProps<
407
+ TStateProps,
408
+ TDispatchProps,
409
+ TOwnProps,
410
+ TMergedProps
411
+ >,
412
+ options?: ConnectOptions<State, TStateProps, TOwnProps, TMergedProps>,
413
+ ): InferableComponentEnhancerWithProps<TMergedProps, TOwnProps>
414
+ // tslint:enable:no-unnecessary-generics
415
+ }
416
+
417
+ let hasWarnedAboutDeprecatedPureOption = false
418
+
419
+ /**
420
+ * @deprecated
421
+ *
422
+ * **We recommend using the `useSelector` and `useDispatch` hooks instead.**
423
+ * See https://react-redux.js.org/api/hooks
424
+ *
425
+ * If you need to use `connect` without this visual deprecation warning,
426
+ * import `legacy_connect` instead:
427
+ *
428
+ * `import { legacy_connect as connect } from 'react-redux'`
429
+ *
430
+ * Connects a React component to a Redux store.
431
+ *
432
+ * - Without arguments, just wraps the component, without changing the behavior / props
433
+ *
434
+ * - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior
435
+ * is to override ownProps (as stated in the docs), so what remains is everything that's
436
+ * not a state or dispatch prop
437
+ *
438
+ * - When 3rd param is passed, we don't know if ownProps propagate and whether they
439
+ * should be valid component props, because it depends on mergeProps implementation.
440
+ * As such, it is the user's responsibility to extend ownProps interface from state or
441
+ * dispatch props or both when applicable
442
+ *
443
+ * @param mapStateToProps A function that extracts values from state
444
+ * @param mapDispatchToProps Setup for dispatching actions
445
+ * @param mergeProps Optional callback to merge state and dispatch props together
446
+ * @param options Options for configuring the connection
447
+ *
448
+ */
449
+ function _connect<
450
+ TStateProps = {},
451
+ TDispatchProps = {},
452
+ TOwnProps = {},
453
+ TMergedProps = {},
454
+ State = unknown,
455
+ >(
456
+ mapStateToProps?: MapStateToPropsParam<TStateProps, TOwnProps, State>,
457
+ mapDispatchToProps?: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
458
+ mergeProps?: MergeProps<TStateProps, TDispatchProps, TOwnProps, TMergedProps>,
459
+ {
460
+ // The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence.
461
+ // @ts-ignore
462
+ pure,
463
+ areStatesEqual = strictEqual,
464
+ areOwnPropsEqual = shallowEqual,
465
+ areStatePropsEqual = shallowEqual,
466
+ areMergedPropsEqual = shallowEqual,
467
+
468
+ // use React's forwardRef to expose a ref of the wrapped component
469
+ forwardRef = false,
470
+
471
+ // the context consumer to use
472
+ context = ReactReduxContext,
473
+ }: ConnectOptions<unknown, unknown, unknown, unknown> = {},
474
+ ): unknown {
475
+ if (process.env.NODE_ENV !== 'production') {
476
+ if (pure !== undefined && !hasWarnedAboutDeprecatedPureOption) {
477
+ hasWarnedAboutDeprecatedPureOption = true
478
+ warning(
479
+ 'The `pure` option has been removed. `connect` is now always a "pure/memoized" component',
480
+ )
481
+ }
482
+ }
483
+
484
+ const Context = context
485
+
486
+ const initMapStateToProps = mapStateToPropsFactory(mapStateToProps)
487
+ const initMapDispatchToProps = mapDispatchToPropsFactory(mapDispatchToProps)
488
+ const initMergeProps = mergePropsFactory(mergeProps)
489
+
490
+ const shouldHandleStateChanges = Boolean(mapStateToProps)
491
+
492
+ const wrapWithConnect = <TProps,>(
493
+ WrappedComponent: ComponentType<TProps>,
494
+ ) => {
495
+ type WrappedComponentProps = TProps &
496
+ ConnectPropsMaybeWithoutContext<TProps>
497
+
498
+ if (process.env.NODE_ENV !== 'production') {
499
+ const isValid = /*#__PURE__*/ isValidElementType(WrappedComponent)
500
+ if (!isValid)
501
+ throw new Error(
502
+ `You must pass a component to the function returned by connect. Instead received ${stringifyComponent(
503
+ WrappedComponent,
504
+ )}`,
505
+ )
506
+ }
507
+
508
+ const wrappedComponentName =
509
+ WrappedComponent.displayName || WrappedComponent.name || 'Component'
510
+
511
+ const displayName = `Connect(${wrappedComponentName})`
512
+
513
+ const selectorFactoryOptions: SelectorFactoryOptions<
514
+ any,
515
+ any,
516
+ any,
517
+ any,
518
+ State
519
+ > = {
520
+ shouldHandleStateChanges,
521
+ displayName,
522
+ wrappedComponentName,
523
+ WrappedComponent,
524
+ // @ts-ignore
525
+ initMapStateToProps,
526
+ initMapDispatchToProps,
527
+ initMergeProps,
528
+ areStatesEqual,
529
+ areStatePropsEqual,
530
+ areOwnPropsEqual,
531
+ areMergedPropsEqual,
532
+ }
533
+
534
+ function ConnectFunction<TOwnProps>(
535
+ props: InternalConnectProps & TOwnProps,
536
+ ) {
537
+ const [propsContext, reactReduxForwardedRef, wrapperProps] =
538
+ React.useMemo(() => {
539
+ // Distinguish between actual "data" props that were passed to the wrapper component,
540
+ // and values needed to control behavior (forwarded refs, alternate context instances).
541
+ // To maintain the wrapperProps object reference, memoize this destructuring.
542
+ const { reactReduxForwardedRef, ...wrapperProps } = props
543
+ return [props.context, reactReduxForwardedRef, wrapperProps]
544
+ }, [props])
545
+
546
+ const ContextToUse: ReactReduxContextInstance = React.useMemo(() => {
547
+ // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.
548
+ // Memoize the check that determines which context instance we should use.
549
+ let ResultContext = Context
550
+ if (propsContext?.Consumer) {
551
+ if (process.env.NODE_ENV !== 'production') {
552
+ const isValid = /*#__PURE__*/ isContextConsumer(
553
+ // @ts-ignore
554
+ <propsContext.Consumer />,
555
+ )
556
+ if (!isValid) {
557
+ throw new Error(
558
+ 'You must pass a valid React context consumer as `props.context`',
559
+ )
560
+ }
561
+ ResultContext = propsContext
562
+ }
563
+ }
564
+ return ResultContext
565
+ }, [propsContext, Context])
566
+
567
+ // Retrieve the store and ancestor subscription via context, if available
568
+ const contextValue = React.useContext(ContextToUse)
569
+
570
+ // The store _must_ exist as either a prop or in context.
571
+ // We'll check to see if it _looks_ like a Redux store first.
572
+ // This allows us to pass through a `store` prop that is just a plain value.
573
+ const didStoreComeFromProps =
574
+ Boolean(props.store) &&
575
+ Boolean(props.store!.getState) &&
576
+ Boolean(props.store!.dispatch)
577
+ const didStoreComeFromContext =
578
+ Boolean(contextValue) && Boolean(contextValue!.store)
579
+
580
+ if (
581
+ process.env.NODE_ENV !== 'production' &&
582
+ !didStoreComeFromProps &&
583
+ !didStoreComeFromContext
584
+ ) {
585
+ throw new Error(
586
+ `Could not find "store" in the context of ` +
587
+ `"${displayName}". Either wrap the root component in a <Provider>, ` +
588
+ `or pass a custom React context provider to <Provider> and the corresponding ` +
589
+ `React context consumer to ${displayName} in connect options.`,
590
+ )
591
+ }
592
+
593
+ // Based on the previous check, one of these must be true
594
+ const store: Store = didStoreComeFromProps
595
+ ? props.store!
596
+ : contextValue!.store
597
+
598
+ const getServerState = didStoreComeFromContext
599
+ ? contextValue!.getServerState
600
+ : store.getState
601
+
602
+ const childPropsSelector = React.useMemo(() => {
603
+ // The child props selector needs the store reference as an input.
604
+ // Re-create this selector whenever the store changes.
605
+ return defaultSelectorFactory(store.dispatch, selectorFactoryOptions)
606
+ }, [store])
607
+
608
+ const [subscription, notifyNestedSubs] = React.useMemo(() => {
609
+ if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY
610
+
611
+ // This Subscription's source should match where store came from: props vs. context. A component
612
+ // connected to the store via props shouldn't use subscription from context, or vice versa.
613
+ const subscription = createSubscription(
614
+ store,
615
+ didStoreComeFromProps ? undefined : contextValue!.subscription,
616
+ )
617
+
618
+ // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
619
+ // the middle of the notification loop, where `subscription` will then be null. This can
620
+ // probably be avoided if Subscription's listeners logic is changed to not call listeners
621
+ // that have been unsubscribed in the middle of the notification loop.
622
+ const notifyNestedSubs =
623
+ subscription.notifyNestedSubs.bind(subscription)
624
+
625
+ return [subscription, notifyNestedSubs]
626
+ }, [store, didStoreComeFromProps, contextValue])
627
+
628
+ // Determine what {store, subscription} value should be put into nested context, if necessary,
629
+ // and memoize that value to avoid unnecessary context updates.
630
+ const overriddenContextValue = React.useMemo(() => {
631
+ if (didStoreComeFromProps) {
632
+ // This component is directly subscribed to a store from props.
633
+ // We don't want descendants reading from this store - pass down whatever
634
+ // the existing context value is from the nearest connected ancestor.
635
+ return contextValue!
636
+ }
637
+
638
+ // Otherwise, put this component's subscription instance into context, so that
639
+ // connected descendants won't update until after this component is done
640
+ return {
641
+ ...contextValue,
642
+ subscription,
643
+ } as ReactReduxContextValue
644
+ }, [didStoreComeFromProps, contextValue, subscription])
645
+
646
+ // Set up refs to coordinate values between the subscription effect and the render logic
647
+ const lastChildProps = React.useRef<unknown>(undefined)
648
+ const lastWrapperProps = React.useRef(wrapperProps)
649
+ const childPropsFromStoreUpdate = React.useRef<unknown>(undefined)
650
+ const renderIsScheduled = React.useRef(false)
651
+ const isMounted = React.useRef(false)
652
+
653
+ // TODO: Change this to `React.useRef<Error>(undefined)` after upgrading to React 19.
654
+ /**
655
+ * @todo Change this to `React.useRef<Error>(undefined)` after upgrading to React 19.
656
+ */
657
+ const latestSubscriptionCallbackError = React.useRef<Error | undefined>(
658
+ undefined,
659
+ )
660
+
661
+ useIsomorphicLayoutEffect(() => {
662
+ isMounted.current = true
663
+ return () => {
664
+ isMounted.current = false
665
+ }
666
+ }, [])
667
+
668
+ const actualChildPropsSelector = React.useMemo(() => {
669
+ const selector = () => {
670
+ // Tricky logic here:
671
+ // - This render may have been triggered by a Redux store update that produced new child props
672
+ // - However, we may have gotten new wrapper props after that
673
+ // If we have new child props, and the same wrapper props, we know we should use the new child props as-is.
674
+ // But, if we have new wrapper props, those might change the child props, so we have to recalculate things.
675
+ // So, we'll use the child props from store update only if the wrapper props are the same as last time.
676
+ if (
677
+ childPropsFromStoreUpdate.current &&
678
+ wrapperProps === lastWrapperProps.current
679
+ ) {
680
+ return childPropsFromStoreUpdate.current
681
+ }
682
+
683
+ // TODO We're reading the store directly in render() here. Bad idea?
684
+ // This will likely cause Bad Things (TM) to happen in Concurrent Mode.
685
+ // Note that we do this because on renders _not_ caused by store updates, we need the latest store state
686
+ // to determine what the child props should be.
687
+ return childPropsSelector(store.getState(), wrapperProps)
688
+ }
689
+ return selector
690
+ }, [store, wrapperProps])
691
+
692
+ // We need this to execute synchronously every time we re-render. However, React warns
693
+ // about useLayoutEffect in SSR, so we try to detect environment and fall back to
694
+ // just useEffect instead to avoid the warning, since neither will run anyway.
695
+
696
+ const subscribeForReact = React.useMemo(() => {
697
+ const subscribe = (reactListener: () => void) => {
698
+ if (!subscription) {
699
+ return () => {}
700
+ }
701
+
702
+ return subscribeUpdates(
703
+ shouldHandleStateChanges,
704
+ store,
705
+ subscription,
706
+ // @ts-ignore
707
+ childPropsSelector,
708
+ lastWrapperProps,
709
+ lastChildProps,
710
+ renderIsScheduled,
711
+ isMounted,
712
+ childPropsFromStoreUpdate,
713
+ notifyNestedSubs,
714
+ reactListener,
715
+ )
716
+ }
717
+
718
+ return subscribe
719
+ }, [subscription])
720
+
721
+ useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [
722
+ lastWrapperProps,
723
+ lastChildProps,
724
+ renderIsScheduled,
725
+ wrapperProps,
726
+ childPropsFromStoreUpdate,
727
+ notifyNestedSubs,
728
+ ])
729
+
730
+ let actualChildProps: Record<string, unknown>
731
+
732
+ try {
733
+ actualChildProps = React.useSyncExternalStore(
734
+ // TODO We're passing through a big wrapper that does a bunch of extra side effects besides subscribing
735
+ subscribeForReact,
736
+ // TODO This is incredibly hacky. We've already processed the store update and calculated new child props,
737
+ // TODO and we're just passing that through so it triggers a re-render for us rather than relying on `uSES`.
738
+ actualChildPropsSelector,
739
+ getServerState
740
+ ? () => childPropsSelector(getServerState(), wrapperProps)
741
+ : actualChildPropsSelector,
742
+ )
743
+ } catch (err) {
744
+ if (latestSubscriptionCallbackError.current) {
745
+ // eslint-disable-next-line no-extra-semi
746
+ ;(err as Error).message +=
747
+ `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\n`
748
+ }
749
+
750
+ throw err
751
+ }
752
+
753
+ useIsomorphicLayoutEffect(() => {
754
+ latestSubscriptionCallbackError.current = undefined
755
+ childPropsFromStoreUpdate.current = undefined
756
+ lastChildProps.current = actualChildProps
757
+ })
758
+
759
+ // Now that all that's done, we can finally try to actually render the child component.
760
+ // We memoize the elements for the rendered child component as an optimization.
761
+ const renderedWrappedComponent = React.useMemo(() => {
762
+ return (
763
+ // @ts-ignore
764
+ <WrappedComponent
765
+ {...actualChildProps}
766
+ ref={reactReduxForwardedRef}
767
+ />
768
+ )
769
+ }, [reactReduxForwardedRef, WrappedComponent, actualChildProps])
770
+
771
+ // If React sees the exact same element reference as last time, it bails out of re-rendering
772
+ // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.
773
+ const renderedChild = React.useMemo(() => {
774
+ if (shouldHandleStateChanges) {
775
+ // If this component is subscribed to store updates, we need to pass its own
776
+ // subscription instance down to our descendants. That means rendering the same
777
+ // Context instance, and putting a different value into the context.
778
+ return (
779
+ <ContextToUse.Provider value={overriddenContextValue}>
780
+ {renderedWrappedComponent}
781
+ </ContextToUse.Provider>
782
+ )
783
+ }
784
+
785
+ return renderedWrappedComponent
786
+ }, [ContextToUse, renderedWrappedComponent, overriddenContextValue])
787
+
788
+ return renderedChild
789
+ }
790
+
791
+ const _Connect = React.memo(ConnectFunction)
792
+
793
+ type ConnectedWrapperComponent = typeof _Connect & {
794
+ WrappedComponent: typeof WrappedComponent
795
+ }
796
+
797
+ // Add a hacky cast to get the right output type
798
+ const Connect = _Connect as unknown as ConnectedComponent<
799
+ typeof WrappedComponent,
800
+ WrappedComponentProps
801
+ >
802
+ Connect.WrappedComponent = WrappedComponent
803
+ Connect.displayName = ConnectFunction.displayName = displayName
804
+
805
+ if (forwardRef) {
806
+ const _forwarded = React.forwardRef(
807
+ function forwardConnectRef(props, ref) {
808
+ // @ts-ignore
809
+ return <Connect {...props} reactReduxForwardedRef={ref} />
810
+ },
811
+ )
812
+
813
+ const forwarded = _forwarded as ConnectedWrapperComponent
814
+ forwarded.displayName = displayName
815
+ forwarded.WrappedComponent = WrappedComponent
816
+ return /*#__PURE__*/ hoistStatics(forwarded, WrappedComponent)
817
+ }
818
+
819
+ return /*#__PURE__*/ hoistStatics(Connect, WrappedComponent)
820
+ }
821
+
822
+ return wrapWithConnect
823
+ }
824
+
825
+ /**
826
+ * * @deprecated
827
+ *
828
+ * **We recommend using the `useSelector` and `useDispatch` hooks instead.**
829
+ * See https://react-redux.js.org/api/hooks
830
+ *
831
+ * If you need to use `connect` without this visual deprecation warning,
832
+ * import `legacy_connect` instead:
833
+ *
834
+ * `import { legacy_connect as connect } from 'react-redux'`
835
+ */
836
+ export const connect: Connect = _connect as Connect
837
+
838
+ /**
839
+ * Connects a React component to a Redux store. Same as `connect` but without
840
+ * the deprecation warning.
841
+ *
842
+ * **We recommend using the `useSelector` and `useDispatch` hooks instead.**
843
+ * See https://react-redux.js.org/api/hooks
844
+ */
845
+ export const legacy_connect: Connect = _connect as Connect