cester2017-11-13 18:08:02
cester, 2017-11-13 18:08:02

A complete SSR example for react/redux?

Good afternoon! Can you please tell me a complete server side rendering example for react/redux? Is there such a thing?
I don’t understand how to make the components universal, perhaps it’s necessary to somehow transfer the state from the back to the client?!
Can I immediately pass the main component on the server when rendering?
Please give some advice on this subject.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Ilya Gerasimov, 2017-11-13

Yes, the state is collected on the server for each client (request'a), let's say at the middleware level we collect the state (the current authorized user, some other global data), then the route handler works, we received some page data from the database and passed them as a context, something like this:

import React from 'react';
import { StaticRouter } from 'react-router'
import { Provider } from 'react-redux'
import ReactDOMServer from 'react-dom/server';

import App from './client/components/App.jsx'

  <Provider store={ReduxStore}>

Where, ReduxStore is the global state (redux) of the request generated by us, Url is the requested url, Context is the context (will be passed as this.props.staticContext to the component). React will pull the desired route container (according to your routes in App) and pass it the context, the component is rendered based on the received data. The result of the renderToString method will be an html string (marked up with React), which we use a template engine or somehow insert into the component mount block (in layout), additionally pass the generated state to the template engine, in the documentation it looks like this:
Now what happens after the page has loaded and the client scripts are picked up? It's just that we pick up the state from window.__PRELOADED_STATE__ and, in general, that's it, the global state is transferred, the component is already rendered, it should be borne in mind that the results during client-rendering and server-rendering should always be the same, just do not use the methods available to the browser, but not available to the server (at the level of the mount and the first render) and carefully monitor your code in terms of memory, otherwise, in case of any leak, the memory on the server will not be cleared after each render.
Something like this, I hope it helped, although there are still quite a few hacks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question