I am currently reading a book about React and Universal applications, in which the author claims that it is best to use the initial state from server to client:
server.js
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import Myapp from '../MyApp';
import api from '../services';
function renderPage(html, initialData) {
return `
<html>
<body>
${html}
</body>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialData)};
</script>
<script src="bundle.js"></script>
</html>
`;
}
export default function(request, reply) {
const initialData = api.getData();
const html = renderToStaticMarkup(<MyApp />);
reply(renderPage(html, initialData);
}
And then, in the client, you will read the data as follows:
bundle.js
const initialData = window.__INITIAL_STATE__ || {};
const mountNode = document.getElementById('root');
ReactDOM.render(<MyApp />, mountNode);
As I understand it, the initial state is first converted to a string, and then attached as a global object to the window object.
This decision looks very rude to me. The book was released in mid-2016. Is there a window.__INITIAL_STATE__way to do this, or are there better solutions?
, , , , , , , .