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
- NextJs - Where can we add a <script> code?
- adding jquery to react starter kit
- Internal data having array of objects could not be rendered
- I am trying to print array inside object using map function but I get :Cannot read property map of undefined
- React: Find out if an element is inside another ref container
- React: Why is the argument empty when calling the function in the onClick event?
- How to call props of a sidebar Component? - Leads to TypeError: Cannot read property 'map' of undefined
- React + backend - project structure when sharing code
- npm "Illegal characters in path" while uninstalling create-react-app
- Count the number of threads on a parent comment in ReactJS
- Warning: Failed prop type: The prop `justify` of `ForwardRef(Grid)` is deprecated. Use `justifyContent` instead, the prop was renamed
- react-rangeslider don't show on bootstrap modal
- CSS Transitions don't survive React Component changing inner DOM structure
- Endless loop in react and socket.io
- Cannot update during an existing state transition when fetching counts
- Hosting React App on Fire base having problem with routing
- How to fix "TypeError: items.map is not a function" when working with React and APIs?
- Error: stream.push() after EOF in react-pdf
- Custom useEffect Second Argument
- Timeout not clearing when used in onChange function
- React error [Expected an assignment or function call and instead saw an expression]
- How to resolve the error from a promise in reactjs
- React Router doesnot match path = "/" in production
- How to deal with data dependencies in a component
- Sharing object aroung Components in React.JS
- How to empty input values and reset state in ReactJS hooks
- Countdown Timer function in React-Redux
- Unable to get JSON response from Express in production
- How can I include my existing table into my export function?
- How to install/import React in TypeScript