3 ms·
React, as it initializes into a server rendered DOM on the client, has a requirement that the server rendered markup is exactly identical to that which it would
by devrandomguy 9y ago
React, as it initializes into a server rendered DOM on the client, has a requirement that the server rendered markup is exactly identical to that which it would have rendered itself as an SPA. TL:DR this is required by the shadow DOM, an optimization that is responsible for much of React's efficiency in browser DOM manipulation.
When your client and server are both running the exact same UI code, then keeping the server rendered HTML in sync with the initial state of the client side DOM, is just a matter of keeping the application state in sync. That is done be serializing it into the response and then reading it from the client side app during init.
But, if the server is using an entirely different codebase to render HTML, then it would take heroic automation to keep that in sync with what the client expects. Better to just use a different type of client side framework, in that case, I guess; seeing React clients backed by servers that are written in neither JS nor compile-to-JS languages is another surprise.
- bsimpson 9y agoI think you're muddy on a couple points: - React doesn't require the existing markup to match - it will happily clobber whatever it finds lurking in its container. The first render is probably faster if it matches, but it isn't like your page is going to crash if they are out-of-sync. - The Shadow DOM is a way to encapsulate styles/state in DOM elements - it's what draws the slider thumb in an <input>, and what allows Web Component styles to use simple selectors like "button" without commandeering the all the buttons on the host page. It has nothing to do with React. I think the phrase you're looking for is "virtual DOM".