4 ms·
Because rendering in a Node process is more complicated when async state is involved - using a browser eliminates that complexity. For simpler apps without any
by jotto 9y ago
Because rendering in a Node process is more complicated when async state is involved - using a browser eliminates that complexity. For simpler apps without any async state (AJAX or WebSockets), a Node process may suffice.
- mcintyre1994 9y agoDumb question because I have very little node experience - I've been doing a node course and it uses a lot of async stuff server side, eg for everything that hits the database (using promises). Why wouldn't you just do that for your async state when you render server side?
- jotto 9y agoYou could indeed do that, it's just more work. The beauty of server-side rendering a React app in a headless browser is that since the environment is the same as what the app was originally designed for (a browser), things _just work_. For example: you load the app in your headless browser and let it load as would in any browser. The browser fires some events and XHR/WebSocket requests and you can cleanly wait for them to finish as opposed to doing something like this: https://techbrunch.gousto.co.uk/2016/10/10/isomorphic-react-v2/ https://techbrunch.gousto.co.uk/2016/10/10/isomorphic-react-... which requires you to do some extra configuration in your app to help support a Node environment. TL;DR: ReactDOMServer.renderToString won't wait for your async requests to finish, you need them to execute and finish before you call renderToString
- underwater 9y agoThis sounds like a major kludge to me. What if the page keeps firing events? What if the page is relying on cues from the browser (dimensions, cookies, JS capabilities, etc.) to know the correct requests to make. If you care about performance you should design an architecture where it's possible to determine exactly which parts should and can be executed on the server.
- artursapek 9y agoAgreed. A react component that can't render something without extra async state updates is a poorly designed react component.
- artursapek 9y agoBut aren't async state changes usually a result of user interaction, or extra network calls? I can't think of an example where an app can't render an initial frame without async state. Sure the state might change after the page loads and JS binds, but that doesn't matter for the purposes this is covering (search engine indexing, faster apparent page load)