In React, client-side rendering (CSR) and server-side rendering (SSR) refer to two different approaches for rendering a web page. Let's break down each approach and provide examples.
Client-Side Rendering (CSR)
In CSR, the entire page is initially loaded as a simple HTML document containing a small JavaScript bundle. React then takes over in the browser and dynamically generates the rest of the UI. This means the user's browser fetches data and generates the user interface.
Advantages:
- More interactive because it provides a single-page application feel.
- Subsequent page navigation is faster as it does not reload the entire page.
Disadvantages:
- Slower initial page load, especially for users on slower connections.
- Can be problematic for SEO because the initial HTML content is minimal.
Example of CSR with Create React App
// index.js (Entry Point of the React App)
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
// Render the app inside the HTML element with the ID "root"
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// App.js
import React from 'react';
const App = () => {
return (
<div>
<h1>Client-Side Rendering in React</h1>
<p>This content is rendered in the browser.</p>
</div>
);
};
export default App;
In this example, the index.js
file uses React to render the App
component entirely in the browser.
Server-Side Rendering (SSR)
In SSR, the server generates the initial HTML content for the page. This means that the server processes the initial state and sends a fully rendered HTML page to the client, which is displayed quickly in the user's browser. Then, React takes over to handle further interactions.
Advantages:
- Faster initial load time due to pre-rendered content.
- Better for SEO because the initial HTML contains relevant content.
Disadvantages:
- More server resource usage because every request requires generating HTML.
- More complexity in setup and development.
Example of SSR with Next.js
Next.js is a popular framework for SSR in React.
// pages/index.js (Entry Point of the Next.js App)
const HomePage = () => {
return (
<div>
<h1>Server-Side Rendering in React</h1>
<p>This content is pre-rendered on the server.</p>
</div>
);
};
export default HomePage;
In this example, Next.js will pre-render the HomePage
component on the server and send the fully formed HTML to the client.
Summary
- Client-Side Rendering: The browser generates and updates the UI. It's suitable for highly interactive applications.
- Server-Side Rendering: The server generates the initial HTML. Ideal for performance and SEO-critical applications.
The choice between CSR and SSR depends on the specific requirements and user experience needs of the application.
Top comments (0)