score:134
For a given website / web-application, you can use react either client-side, server-side or both.
Client-Side
Over here, you are completely running ReactJS on the browser. This is the simplest setup and includes most examples (including the ones on http://reactjs.org). The initial HTML rendered by the server is a placeholder and the entire UI is rendered in the browser once all your scripts load.
Server-Side
Think of ReactJS as a server-side templating engine here (like jade, handlebars, etc...). The HTML rendered by the server contains the UI as it should be and you do not wait for any scripts to load. Your page can be indexed by a search engine (if one does not execute any javascript).
Since the UI is rendered on the server, none of your event handlers would work and there's no interactivity (you have a static page).
Both
Here, the initial render is on the server. Hence, the HTML received by the browser has the UI as it should be. Once the scripts are loaded, the virtual DOM is re-rendered once again to set up your components' event handlers.
Over here, you need to make sure that you re-render the exact same virtual DOM (root ReactJS component) with the same props
that you used to render on the server. Otherwise, ReactJS will complain that the server-side and client-side virtual DOMs don't match.
Since ReactJS diffs the virtual DOMs between re-renders, the real DOM is not mutated. Only the event handlers are bound to the real DOM elements.
score:3
Is it 2 separate ways to build the application, or can they be used together?
They can be used together.
If we can use it together, how to do it - do we need to duplicate the same elements on the server side and client side? Or, can we just build the static parts of our application on the server, and the dynamic parts on the client side, without any connection to the server side that was already pre-rendered?
It's better to have the same layout being rendered to avoid reflow and repaint operations, less flicker / blinks, your page will be smoother. However, it's not a limitation. You could very well cache the SSR html (something Electrode does to cut down response time) / send a static html which gets overwritten by the CSR (client side render).
If you're just starting with SSR, I would recommend start simple, SSR can get very complex very quickly. To build html on the server means losing access to objects like window, document (you have these on the client), losing ability to incorporate async operations (out of the box), and generally lots of code edits to get your code SSR compatible (since you'll have to use webpack to pack your bundle.js). Things like CSS imports, require vs import suddenly start biting you (this is not the case in default React app without webpack).
The general pattern of SSR looks like this. An Express server serving requests:
const app = Express();
const port = 8092;
// This is fired every time the server side receives a request
app.use(handleRender);
function handleRender(req, res) {
const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
console.log('fullUrl: ', fullUrl);
console.log('req.url: ', req.url);
// Create a new Redux store instance
const store = createStore(reducerFn);
const urlToRender = req.url;
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={urlToRender} context={{}}>
{routes}
</StaticRouter>
</Provider>
);
const helmet = Helmet.renderStatic();
// Grab the initial state from our Redux store
const preloadedState = store.getState();
// Send the rendered page back to the client
res.send(renderFullPage(helmet, html, preloadedState));
}
My suggestion to folks starting out with SSR would be to serve out static html. You can get the static html by running the CSR SPA app:
document.getElementById('root').innerHTML
Don't forget, the only reasons to use SSR should be:
- SEO
- Faster loads (I would discount this)
Hack : https://medium.com/@gagan_goku/react-and-server-side-rendering-ssr-444d8c48abfc
score:4
I was actually wondering the same researching quite a bit and while the answer you are looking for was given in the comments but I feel it should be more prominent hence I'm writing this post (which I will update once I can come up with a better way as I find the solution architecturally at least questionable).
You would need to write your components with both ways in mind thus basically putting if
switches everywhere to determine whether you are on the client or the server and then do either as DB query (or whatever appropriate on the server) or a REST call (on the client). Then you would have to write endpoints which generate your data and expose it to the client and there you go.
Again, happy to learn about a cleaner solution.
score:65
Image source: Walmart Labs Engineering Blog
NB: SSR (Server Side Rendering), CSR (Client Side Rendering).
The main difference being that with SSR, the servers response to the clients browser, includes the HTML of the page to be rendered. It is also important to note that although, with SSR, the page renders quicker. The page will not be ready for user interaction until JS files have been downloaded and the browser has executed React.
One downside is that the SSR TTFB (Time to First Byte) can be slightly longer. Understandably so, because the server takes some time creating the HTML document, which in turn increases the servers response size.
Source: stackoverflow.com
Related Query
- ReactJS Server side rendering in Flask
- ReactJS server side rendering fo single page application
- ReactJS server side rendering and componentDidMount method
- Microservices UI Frontend with Java and ReactJS Server Side Rendering
- React SSR: Prevent client side rendering of components which are rendered on the server
- ReactJS using cookie while rendering on server side
- How we can convert client side rendering react js app to server side rendering using react router 4?
- Owl Carousel 2 server side rendering in Reactjs
- How to pass data in server side rendering to reactjs component from node
- React Server side rendering with Express - warning on the client checksum & Styling
- react server side rendering with client side routing
- Next.js client side protected routes without server side rendering
- React JS : Migrate from server rendering to pure client side
- Server side rendering generating different markup than client side rendering
- Rendering ReactJS from asynchronous server side data calls
- React server side rendering is not updating after client side route change
- ReactJs.net Server Side Rendering with client initialization throws warning
- How to setup multistage builds for a ReactJS App with server side rendering
- Converting client side rendering to server side rendering of existing react application
- Rails 5 Redux React Server Side Rendering gives client side JavaScript warning 'Replacing React-rendered children with a new...'
- How do I connect the frontend ReactJS socket client to the server side socket?
- Unable to get dynamic component in Next.js to skip server side rendering and show only on the client
- Next js - disable server side rendering on some pages
- Server side rendering with react, react-router, and express
- React Server side rendering of CSS modules
- React.js server side rendering with PHP
- Webpack 4 and react loadable does not seems to create correct chunk for server side rendering
- React.js server side rendering with Java [without Node.js]
- Server side rendering with async data fetch
- Material UI v5 server side rendering css order not working with gatsby
More Query from same tag
- Convert from getElementById to useRef in REact
- Formik, ReactJs, set focus and remove focus when check and uncheck a checkbox
- Not able to change the state of a CheckBox in React Native
- How to make react router work with static assets, html5 mode, history API and nested routes?
- How to set file object in state with React hooks?
- Passing props to functional React component in Typescript
- Special characters in hasura graphql queries
- How to implement Drop down in React JS using Array for the below snippet of code
- ReactJs security
- Framer motion Follow same duration on hover end
- Passing States with Redirect
- React js createRef() show typescript error
- Error "No 'Access-Control-Allow-Origin' header is present on the requested resource" even after setting headers on server and client
- Which way to use to replace a complete object with useState()?
- multiple outputs for webpack
- axios remove / before get request
- How to Pass properties from array of objects to api request
- MUIdatatables how to navigate using arrow/tab keys?
- Method returning as undefined when using connect from React-redux
- Passing dynamic color to Material-UI Icon
- React-semantic-ui with route errors
- withFormik how to access wrapped form's props in handleSubmit
- Theme with React and Redux
- react prop not rendering in parent component and even in the same one
- How to proxy API REST calls : (FE hosted on Netlify)?
- React - TypeError: Cannot read property 'setState' of undefined (Arrow functions)
- Why am I getting a 400 response with a type error for my GraphQL query?
- upload image file converted from html to s3
- Javascript promises catch block initiating when no error
- React Router v4 fetch data based on params