How “hydration” works with react server components? - reactjs

With SSR, JavaScript must be fetched for interactivity, which is often achieved via hydration. How will this be achieved with server components?

React server components don't have state, event handlers, etc. and cannot themselves be interactive. But they can be interleaved with client components, which can be interactive.
Also - React server components still require Javascript. Even for server components, even though no bundles are sent down, they are still "hydrated" in the sense that they are turned into JSX elements and then rendered onto the page as part of the React tree.
See https://blog.plasmic.app/posts/how-react-server-components-work/ for a complete look:
Why invent a whole new wire format? The goal on the client is to reconstruct the React element tree. It is much easier to accomplish this from this format than from html, where we’d have to parse the HTML to create the React elements. Note that the reconstruction of the React element tree is important, as this allows us to merge subsequent changes to the React tree with minimal commits to the DOM.

Related

React + SSR: Correct way to handle a component that needs to fetch data first

I currently have a React app that I'd like to use SSR with. All but one component is pretty much static content, making SSR super easy. Everything but the component is rendered just fine and well right now.
My question is how do I go about rendering this component that needs to first get data? Because it's a complex SVG that gets rendered my line of thinking is that having it "update" once data comes in is a bad move, and it would be better for it to just not exist in the absence of data (with an error message).
So here's my plan: I can add a prop to the component to pass in data from a parent rather than keep it as internal state only. So if data is passed, no fetch request in the component is necessary. From there what I can do is take the static bundle output of the app and, when the page is requested, the server will request the proper data just as the component would. Once the data is received, the server can grab the component from the bundle with regex, add the data as a prop, render the component, and stick it back in with the rest of the already rendered static content.
Is this the correct way to do this? It feels a bit complicated, but that might just be how it's done. I'm not sure.
Your intuitions are correct. In current React (17.0), it's quite cumbersome to do SSR with data-fetching inside components.
What needs to be achieved on a conceptual level is that all data dependencies need to be known upfront, ie. before calling ReactDOM's render. This way, one can access the data in a synchronous manner which allows to do one-pass render on a server.
I don't quite follow your idea to "grap the component from the bundle with regex". One way of solving the data dependency problem is to inject the data into React tree from the root component (ie. ReactDOM.renderToString(<App componentStaticData={data} />)) and make the data-dependent component aware of the fact that it can just grab the data from there instead of doing (asynchronous) call. It's important to note that useEffects are not executed on the server.
Another idea to grab all the data dependencies is to do two-pass render. First one is used as a way to collect all resources used, then we await their completion and inject them as static data into send pass.
Third way is to use one of the React frameworks that provide SSR out of the box. You can have a look at (among many others) Next.js or Gatsby. Depending on your setup, this might be easiest or the hardest way to achieve SSR.

Server side rendering react - Virtual DOM?

I recently started looking into SSR(Server side rendering) and I am impressed with its advantages. To name a few Load times, SEO, No javascript configuration.
However I am trying to understand if react server side rendering is worth it.
React is known for its Virtual DOM manipulations but using react with server side rendering will not give benefits of reactJs.
Can some one shed your ideas on using reactJS for server side rendering?
Using server-side rendering in React does not imply that React will not be used on client-side.
One of completely valid approaches is to start with client-side rendering only. In this case you have to setup a single HTML element in your HTML file that will become a hook for React once it loads.
Just to give you an example, let's say we have an <div id="root"></div> element in index.html file that will be served if we HTTP GET / path on our server. Initial document (in our case index.html) should also reference javascript file that includes React and our code. It can be done by adding something like <script type="text/javascript" src="/index.js"></script> just before </body> tag.
At some point while index.js is executed, ReactDOM.render() method is called (note: we are in the browser right now) - this is a moment in time when React looks for a div element with root id attached in a document. After it's found, it becomes react-root - component tree is mounted under this element and managed by React (ie. virtual DOM, event handlers, state updates).
Please note that this approach requires that at least one javascript file is fetched, parsed and executed before browser can render anything meaningful (other than an empty div) to a user. For some scenarios, this is not acceptable and this is where SSR (server-side rendering) can help.
Server-side rendering requires that you have JavaScript runtime environment available on your server. One of the popular choices is Node.js (others include for example Nashron for JVM).
In approach, you execute React on the server and use ReactDOMServer.renderToString() (or ReactDOMServer.renderToNodeStream()) method to generate HTML response that is sent to the client - instead of an almost empty response with just one placeholder div as previously, now you can send all the markup that will be generated from your component tree (important note here is that in React 16.4(+) only UNSAFE_componentWillMount lifecycle method is called on server-side). After the initial response with a document is sent to the client, browser can render the initial markup before index.js even finishes downloading. Once it does, ReactDOM.hydrate() method kicks in. Hydration is a process of using existing server-side rendered markup and "watering" it with javascript goodies like event handlers. After it's done, this component tree is now completely managed by React with all the benefits.
Please note that in SSR, exactly the same component tree is rendered on a server-side and that's then hydrated on a client-side.
Of course, React can also be used instead of templating engines as a very powerful static HTML markup generator. All you need to do is to render the markup on the server with ReactDOMServer. renderToStaticMarkup() and send it to the client. It should be noted that this approach has a significant performance impact (https://malloc.fi/performance-cost-of-server-side-rendered-react-node-js) and uses a very limited number of React features.

React Redux Server side rendered rerendering on client again

I created server side rendering with approach described in redux's official site, everything is great, but on client side it rendering components again, and this is not good I think. I am passing same state from server to window.__STATE__ variable and passing this to my client side createStore method as initial state, but it rerendering again.
Also please write in comments which part of code is needed to you, if so.
I am not providing since it is very similar to official page instructions code and there is no errors, just issue with rerendering, but as I understand it is not connecting to virtual DOM.
Please help me find valid way for handling this task.
Take a look at this example from the ReactGo project: https://github.com/reactGo/reactGo/blob/master/app/client.jsx#L22
They use a function onUpdate that has the conditional
if (window.__INITIAL_STATE__ !== null) {
window.__INITIAL_STATE__ = null;
return;
}
which prevents a duplicate fetches if __INITIAL_STATE__ is already defined. Your components rerendering may have something to do with the duplicate fetching.
Perhaps I am not understanding what you mean by re-rendering, but it is supposed to "re-render" on the client again. The way isomorphic works is that it renders the HTML on the server, and then the payload includes the initial state as well has the HTML markup - this way the browser "appears" to have faster page load times - since the UI is rendered even before the script is executed. Now once the HTML parsed and the script runs, React internally builds the virtual DOM and then compares it to the server generated DOM and wires up event listeners etc. It does not however, do a full re-render in that no new DOM elements should be created. If for any reason the client run of your React render results in a virtual DOM that is different from the generated server DOM, React will give you a warning.
"Warning: React attempted to reuse markup in a container but the
checksum was invalid. This generally means that you are using server
rendering and the markup generated on the server was not what the
client was expecting. React injected new markup to compensate which
works but you have lost many of the benefits of server rendering.
Instead, figure out why the markup being generated is different on the
client or server:"

Issue with UI event when rendering component inside a web component shadow DOM

I'm facing some issues when rendering a React component into the shadow DOM of a webcomponent.
I wrote a small piece of code to turn a React component into a webcomponent, but I want to render the
React component inside the shadow DOM of the webcomponent. But in that case, it seems that React is not able to catch UI events (click, keyPress, etc ...) anymore.
Let's take an example, let say that I have a first webcomponent <awesome-timer /> that render the React component inside the webcomponent node, and another webcomponent <less-awesome-timer /> that render the React component inside the shadow DOM of the webcomponent.
Both webcomponents use the same React component. However the one rendered inside the shadow DOM does not work, because click events on the button of the timer component does not trigger the bound function.
I guess React is not designed to handle such case, but I'd love to get more details about it.
The code of the example is available here : https://gist.github.com/mathieuancelin/cca14d31184bf4468bc1
Does anyone have an idea about it ?
I know this is kinda late but, I believe your issue when you pass any attributes to a web component they instantly become strings Because that's all you can pass to a web component. Now of course you can convert or cast them back to there original data type, except functions because once stringified they loose there scoping, lexical and all.
Now to your main question, you are were trying to pass you child element through the Main web components slot. Now you have to remember that once you pass anything to a web component you now have to use the webs components methods and return types to manage whatever you pass. So yes passing react into a web component will not work they you expect.
You will need to go back to whatever tool you use to build your web component and deal with the slot logic there. Since this is a very old post as are web components. You might not have had access to the modern web component build tool's we have today. I found Stenicl allows you to build and manage your web components in Typescript.
A good option is to change your pattern a little bit and just return web components from your react app.
Or you can use another really cool to call Lit-HTML or Lit-element. I believe they may have combined there core libraries. Anyway these tool will allow you to combine Reactjs and web components where lit-html gives you access to methods simial to Reactjs's life cycle methods. Anyway some good stuff to check out if your stuck at this point.

Reuse markup from react component in single-page, client-side only webapp

React relies on the data-react-checksum attribute for reusing markup, which is only set in renderComponentToString (used for server-side rendering of components).
How can I reuse the react-component markup when the component is rendered client-side only?
Background
I'm working on a client-side only webapp. One of the project's goals is to render as quickly as possible, reducing UI "lag" from uninitialized elements, JS loading/parsing, and so forth.
I'm want to cache the rendered react-components markup using localStorage so the previous UI state can be restored as early as possible (again for performance reasons without waiting ~200ms for react to be loaded and parsed).
Strictly speaking, there's no way to turn a string of markup into a live React component (at least not in a performant way). Plus, it doesn't really make sense as your component might have had hidden state that aren't shown on the final rendered DOM string. If you try to revert the string into a component, it'll lead to state inconsistencies.
Something neat to do is to serialize your data into localStorage, and then reproduce your components from that data. But this more or less helps in your case.
But still, you can roll your own small logic on putting the string markup, then letting React destroy it subsequently by rendering a second time.

Resources