React Server Components (RSC) provide a great way to enhance full-stack React applications by fetching and rendering data directly from the server. This allows for dynamic content without sending a lot of JavaScript to the client, making the app more performant and scalable. In this tutorial, we will implement dynamic data fetching in React Server Components and display data from an external API.
Step 1 - Setting Up the Project
Start by creating a new React app with Express to set up the server-side environment for React Server Components.
npx create-react-app dynamic-fetch-app
cd dynamic-fetch-app
npm install express react-server-dom
Next, create the Express server in the server.js
file:
// server.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./src/App');
const app = express();
app.get('/', (req, res) => {
const appString = ReactDOMServer.renderToString();
res.send(`
Dynamic Data Fetching
${appString}
`);
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Step 2 - Creating the Component for Data Fetching
In this step, we will create a component that will fetch data from a public API (for example, the JSONPlaceholder API for users).
// DataFetcher.js
import React, { useEffect, useState } from 'react';
const DataFetcher = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const result = await response.json();
setData(result);
setLoading(false);
};
fetchData();
}, []);
if (loading) {
return Loading...;
}
return (
<h2>User List</h2>
<ul>
{data.map(user => (
<li>
{user.name} - {user.email}
</li>
))}
</ul>
);
};
export default DataFetcher;
Step 3 - Rendering Data in React Server Components
Next, let's use the DataFetcher
component in our main App.js
file. We will ensure that the server fetches and pre-renders the data when the page is served.
// App.js
import React from 'react';
import DataFetcher from './DataFetcher';
const App = () => {
return (
<h1>Dynamic Data Fetching with React Server Components</h1>
);
};
export default App;
Step 4 - Server-Side Rendering of the Component
To use React Server Components for rendering the DataFetcher
component server-side, we will modify our server.js
file to pass the fetched data directly to the component during rendering.
// server.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./src/App');
const app = express();
app.get('/', async (req, res) => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
const appString = ReactDOMServer.renderToString();
res.send(`
Dynamic Data Fetching
${appString}
`);
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
In this updated version of server.js
, we fetch the data from the API before rendering the React app, ensuring that the data is available when the page is served to the user.
Use Case Scenario
In a content-heavy application like a blog or e-commerce site, dynamic data fetching is a common requirement. By fetching the data server-side and rendering it with React Server Components, we can deliver content to the user quickly, even if it is coming from an external API. This improves the overall performance of the app by reducing the amount of JavaScript sent to the client and ensuring faster load times.
✅ Pros and ❌ Cons
✅ Pros:
- ⚡ Fast loading times due to server-side rendering.
- 🧑💻 Simple integration with external APIs for dynamic content.
- 📉 Reduced client-side JavaScript, improving app performance.
❌ Cons:
- 🔄 More complexity in handling data fetching and server-side rendering.
- 🧩 Requires a backend server to handle data fetching and rendering.
- ⚙️ Potential challenges with data synchronization between client and server.
Summary
In this article, we implemented dynamic data fetching in React Server Components. We fetched data from an external API server-side, reducing the client-side load and improving performance. This approach is ideal for applications that need to display dynamic content while minimizing JavaScript execution on the client side.
If you're interested in learning more about React Server Components and full-stack development, check out my guide:
Mastering React Server Components: A Pro Guide to Modern Full-Stack React – just $5.
If this was helpful, you can also support me here: Buy Me a Coffee ☕
Top comments (0)