Server Components in React
Provide an example of using server components to render portions of the React app on the server, optimizing bundle sizes and reducing load times.
const { Suspense } = require('react');
// This component is only rendered on the server and passed to the client
function ServerComponent() {
// Mock data fetching
const data = 'Server-side Rendered Data';
return (
<div>
<h1>{data}</h1>
</div>
);
}
module.exports = ServerComponent;
This is a simple server component that mocks fetching data and displays it. The component will be rendered on the server side.
const React = require('react');
const { Suspense } = require('react');
const ServerComponent = require('./ServerComponent.server');
function App() {
return (
<div>
<h1>Client Component</h1>
<Suspense fallback={<div>Loading...</div>}>
<ServerComponent />
</Suspense>
</div>
);
}
module.exports = App;
This is the client component that utilizes the Suspense component from React to defer rendering the server component until it is ready. `fallback` provides a loading state while waiting.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Server Components Example</title>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script> <!-- Client-side React code bundle -->
</body>
</html>
This is the HTML file where our React app will be mounted. The `bundle.js` is the client-side JavaScript bundle.
body {
font-family: Arial, sans-serif;
}
h1 {
color: #333;
}
Basic CSS styles for the body and h1 elements that could be part of the React application.