Skip to content

Commit bc4569f

Browse files
committed
Add tentative SSR support for useSelector
1 parent ce83bf8 commit bc4569f

File tree

3 files changed

+15
-6
lines changed

3 files changed

+15
-6
lines changed

src/components/Context.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export interface ReactReduxContextValue<
88
> {
99
store: Store<SS, A>
1010
subscription: Subscription
11+
getServerState?: () => SS
1112
}
1213

1314
export const ReactReduxContext =

src/components/Provider.tsx

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,40 @@ import { createSubscription } from '../utils/Subscription'
44
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect'
55
import { Action, AnyAction, Store } from 'redux'
66

7-
export interface ProviderProps<A extends Action = AnyAction> {
7+
export interface ProviderProps<A extends Action = AnyAction, S = any> {
88
/**
99
* The single Redux store in your application.
1010
*/
11-
store: Store<any, A>
11+
store: Store<S, A>
12+
13+
/**
14+
* An optional server state snapshot. Will be used during initial hydration render if available, to ensure that the UI output is consistent with the HTML generated on the server.
15+
*/
16+
serverState?: S
17+
1218
/**
1319
* Optional context to be used internally in react-redux. Use React.createContext() to create a context to be used.
1420
* If this is used, you'll need to customize `connect` by supplying the same context provided to the Provider.
1521
* Initial value doesn't matter, as it is overwritten with the internal state of Provider.
1622
*/
17-
context?: Context<ReactReduxContextValue<any, A>>
23+
context?: Context<ReactReduxContextValue<S, A>>
1824
children: ReactNode
1925
}
2026

2127
function Provider<A extends Action = AnyAction>({
2228
store,
2329
context,
2430
children,
31+
serverState,
2532
}: ProviderProps<A>) {
2633
const contextValue = useMemo(() => {
2734
const subscription = createSubscription(store)
2835
return {
2936
store,
3037
subscription,
38+
getServerState: serverState ? () => serverState : undefined,
3139
}
32-
}, [store])
40+
}, [store, serverState])
3341

3442
const previousState = useMemo(() => store.getState(), [store])
3543

src/hooks/useSelector.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,13 @@ export function createSelectorHook(
4848
}
4949
}
5050

51-
const { store } = useReduxContext()!
51+
const { store, getServerState } = useReduxContext()!
5252

5353
const selectedState = useSyncExternalStoreWithSelector(
5454
store.subscribe,
5555
store.getState,
5656
// TODO Need a server-side snapshot here
57-
store.getState,
57+
getServerState || store.getState,
5858
selector,
5959
equalityFn
6060
)

0 commit comments

Comments
 (0)