Unverified Commit 5eafc1e9 authored by Chandu's avatar Chandu Committed by GitHub

refactor(with-redux): update example to use getStaticProps (#13378)

@lfades hope this works. I have updated the example to show differences between client/ssr/ssg initial state in redux. Let me know if something needs to be changed.
parent e6eb32f6
...@@ -2,7 +2,17 @@ ...@@ -2,7 +2,17 @@
This example shows how to integrate Redux in Next.js. This example shows how to integrate Redux in Next.js.
Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use redux that also works with Next.js's universal rendering approach. Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use Redux that also works with Next.js's universal rendering approach.
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color (black) than the client one (grey).
To illustrate SSG and SSR, go to `/ssg` and `/ssr`, those pages are using Next.js data fetching methods to get the date in the server and return it as props to the page, and then the browser will hydrate the store and continue updating the date.
The trick here for supporting universal Redux is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish on `store.js`.
All components have access to the Redux store using `useSelector`, `useDispatch` or `connect` from `react-redux`.
On the server side every request initializes a new store, because otherwise different user data can be mixed up. On the client side the same store is used, even between page changes.
## Deploy your own ## Deploy your own
...@@ -42,15 +52,3 @@ yarn dev ...@@ -42,15 +52,3 @@ yarn dev
``` ```
Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)). Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
## Notes
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color (black) than the client one (grey).
The Redux `Provider` is implemented in `lib/redux.js`. Since the `IndexPage` component is wrapped in `withRedux` the redux context will be automatically initialized and provided to `IndexPage`.
All components have access to the redux store using `useSelector`, `useDispatch` or `connect` from `react-redux`.
On the server side every request initializes a new store, because otherwise different user data can be mixed up. On the client side the same store is used, even between page changes.
The example under `components/counter.js`, shows a simple incremental counter implementing a common Redux pattern of mapping state to props. Again, the first render is happening in the server and instead of starting the count at 0, it will dispatch an action in redux that starts the count at 1. This continues to highlight how each navigation triggers a server render first and then a client render when switching pages on the client side.
import React from 'react'
import { useSelector, shallowEqual } from 'react-redux' import { useSelector, shallowEqual } from 'react-redux'
const useClock = () => { const useClock = () => {
......
import React from 'react'
import { useSelector, useDispatch } from 'react-redux' import { useSelector, useDispatch } from 'react-redux'
const useCounter = () => { const useCounter = () => {
......
import Link from 'next/link'
const Nav = () => {
return (
<nav>
<Link href="/">
<a>Index</a>
</Link>
<Link href="/ssg">
<a>SSG</a>
</Link>
<Link href="/ssr">
<a>SSR</a>
</Link>
<style jsx>
{`
a {
margin-right: 25px;
}
`}
</style>
</nav>
)
}
export default Nav
import { useDispatch } from 'react-redux'
import useInterval from '../lib/useInterval'
import Clock from './clock'
import Counter from './counter'
import Nav from './nav'
export default function Page() {
const dispatch = useDispatch()
// Tick the time every second
useInterval(() => {
dispatch({
type: 'TICK',
light: true,
lastUpdate: Date.now(),
})
}, 1000)
return (
<>
<Nav />
<Clock />
<Counter />
</>
)
}
import React from 'react'
import { Provider } from 'react-redux' import { Provider } from 'react-redux'
import { initializeStore } from '../store' import { initializeStore } from '../store'
import App from 'next/app' import App from 'next/app'
export const withRedux = (PageComponent, { ssr = true } = {}) => { export const withRedux = (PageComponent) => {
const WithRedux = ({ initialReduxState, ...props }) => { const WithRedux = ({ initialReduxState, ...props }) => {
const store = getOrInitializeStore(initialReduxState) const store = initializeClientSideStore(initialReduxState)
return ( return (
<Provider store={store}> <Provider store={store}>
<PageComponent {...props} /> <PageComponent {...props} />
...@@ -29,44 +28,21 @@ export const withRedux = (PageComponent, { ssr = true } = {}) => { ...@@ -29,44 +28,21 @@ export const withRedux = (PageComponent, { ssr = true } = {}) => {
WithRedux.displayName = `withRedux(${displayName})` WithRedux.displayName = `withRedux(${displayName})`
} }
if (ssr || PageComponent.getInitialProps) {
WithRedux.getInitialProps = async (context) => {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const reduxStore = getOrInitializeStore()
// Provide the store to getInitialProps of pages
context.reduxStore = reduxStore
// Run getInitialProps from HOCed PageComponent
const pageProps =
typeof PageComponent.getInitialProps === 'function'
? await PageComponent.getInitialProps(context)
: {}
// Pass props to PageComponent
return {
...pageProps,
initialReduxState: reduxStore.getState(),
}
}
}
return WithRedux return WithRedux
} }
let reduxStore let reduxStore
const getOrInitializeStore = (initialState) => {
// Always make a new store if server, otherwise state is shared between requests
if (typeof window === 'undefined') {
return initializeStore(initialState)
}
export const initializeServerSideStore = (initialState) => {
// Always make a new store if server ('getStaticProps' or 'getServerSideProps'), to avoid sharing the state between requests.
// Check ssg.js and ssr.js pages for usage
return initializeStore(initialState)
}
export const initializeClientSideStore = (initialState) => {
// Create store if unavailable on the client and set it on the window object // Create store if unavailable on the client and set it on the window object
if (!reduxStore) { if (!reduxStore) {
reduxStore = initializeStore(initialState) reduxStore = initializeStore(initialState)
} }
return reduxStore return reduxStore
} }
import { Provider } from 'react-redux'
import { useStore } from '../store'
export default function App({ Component, pageProps }) {
const store = useStore(pageProps.initialReduxState)
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
import React from 'react' import Page from '../components/page'
import { useDispatch } from 'react-redux'
import { withRedux } from '../lib/redux'
import useInterval from '../lib/useInterval'
import Clock from '../components/clock'
import Counter from '../components/counter'
const IndexPage = () => { export default function Index() {
// Tick the time every second return <Page />
const dispatch = useDispatch()
useInterval(() => {
dispatch({
type: 'TICK',
light: true,
lastUpdate: Date.now(),
})
}, 1000)
return (
<>
<Clock />
<Counter />
</>
)
} }
IndexPage.getInitialProps = ({ reduxStore }) => {
// Tick the time once, so we'll have a
// valid time before first render
const { dispatch } = reduxStore
dispatch({
type: 'TICK',
light: typeof window === 'object',
lastUpdate: Date.now(),
})
return {}
}
export default withRedux(IndexPage)
import Page from '../components/page'
export default function SSG() {
return <Page />
}
// If you build and start the app, the date returned here will have the same
// value for all requests, as this method gets executed at build time.
export function getStaticProps() {
// Note that in this case we're returning the state directly, without creating
// the store first (like in /pages/ssr.js), this approach can be better and easier
return {
props: {
initialReduxState: {
lastUpdate: Date.now(),
light: false,
},
},
}
}
import Page from '../components/page'
import { initializeStore } from '../store'
export default function SSR() {
return <Page />
}
// The date returned here will be different for every request that hits the page,
// that is because the page becomes a serverless function instead of being statically
// exported when you use `getServerSideProps` or `getInitialProps`
export function getServerSideProps() {
const reduxStore = initializeStore()
const { dispatch } = reduxStore
dispatch({
type: 'TICK',
light: false,
lastUpdate: Date.now(),
})
return { props: { initialReduxState: reduxStore.getState() } }
}
import { useMemo } from 'react'
import { createStore, applyMiddleware } from 'redux' import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension' import { composeWithDevTools } from 'redux-devtools-extension'
let store
const initialState = { const initialState = {
lastUpdate: 0, lastUpdate: 0,
light: false, light: false,
...@@ -35,10 +38,37 @@ const reducer = (state = initialState, action) => { ...@@ -35,10 +38,37 @@ const reducer = (state = initialState, action) => {
} }
} }
export const initializeStore = (preloadedState = initialState) => { function initStore(preloadedState = initialState) {
return createStore( return createStore(
reducer, reducer,
preloadedState, preloadedState,
composeWithDevTools(applyMiddleware()) composeWithDevTools(applyMiddleware())
) )
} }
export const initializeStore = (preloadedState) => {
let _store = store ?? initStore(preloadedState)
// After navigating to a page with an initial Redux state, merge that state
// with the current state in the store, and create a new store
if (preloadedState && store) {
_store = initStore({
...store.getState(),
...preloadedState,
})
// Reset the current store
store = undefined
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return _store
}
export function useStore(initialState) {
const store = useMemo(() => initializeStore(initialState), [initialState])
return store
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment