Universal rendering with React and Redux
How to set up a universal React web application with Redux.
Redux is a library that helps manage your state using Flux-like principles. Install it and its official React bindings:
$ npm install redux react-redux
Let’s add Redux on the server-side.
At the top of
routes/index.jsx, import Redux and Provider:
Then create a reducer that doesn’t do anything except return the default state that it’s provided:
Now create the store with the props as the initial state:
Finally, update the top-level component to Provider:
You’ll notice that RouterContext's
createElement prop is removed. That’s because Redux now manages the state so it’s no longer necessary to merge the props in RouterContext.
routes/index.jsx should now look like this:
To maintain isomorphism, update
The only difference is that the store’s initial state comes from
window.PROPS because this file is run in the browser.
Since we’re using JSX in
client.js, we must import
React and make it available.
Don’t forget to restart webpack in the command-line:
# press Ctrl-C to stop the running process first$ webpack -w
routes/routes.jsx and remove Router's
createElement prop. The file should look like the following:
Connect Component To Store
views/Layout.jsx to the Provider store.
connect at the top of the file:
Then create a higher-order component (HOC) that maps the store’s state to the connected component’s props:
As you can see here, the store state from Provider is mapped to Layout’s
props.custom with the help of React context.
Assign the existing component to the variable
Layout and pass it in the wrapper to create the connected component:
views/Layout.jsx should look something like this:
When you switch the browser and refresh, you should see that everything still looks and works the same.
If you have React Developer Tools installed, you can confirm that the data is being passed from Connect to Layout.