
React server components are the features enjoyed by developers and software engineers particularly on the server side. When working with React you can easily design appealing and responsive frontend designs. React is a powerful frontend framework in Javascript library used for building user interfaces and works on component based architecture.
With React Server components React can easily run exclusively on the server. In this blog, we will learn about the working and significance of React server components.
It can fetch data directly from the database or APIs during rendering. These components can fetch data faster from the source as they are present on the server. They have access to file systems and databases and hence do not need to make a roundtrip over the network.
For example, let us take a case where we have to display books from the MongoDB server. We will use React server components to make it work.
| // app/page.jsx (or any server component file) import { dbConnect } from '@/lib/dbConnect'; // Your DB connection utility import BookList from './components/BookList'; // A client component for UI import Book from '@/models/book'; // Your Mongoose model export default async function Home() { // Connect to MongoDB await dbConnect(); // Fetch all books const allBooks = await Book.find(); // Log to server console console.log('Books:', allBooks); // Pass data to a client-side component return ( <main> <h1>All Books</h1> <BookList books={allBooks} /> </main> ); } |
| “React server components are a feature of React which allows you to execute some components on the server and reduce the client bundle size.” |
When a user visits a page, RSC on the server can fetch data from databases, access environment variables and run server only logic easily. It does not send all Javascript to the browser and sends ready made HTML to the client which enables faster loading time and smaller bundle sizes.
| const data = await fetch('https://api.example.com/data'); |
React Server Components also suffer from some disadvantages along with the loads of features it offers. Let us know about some limitations of this React component.
| // This is a Server Component by default export default function Page() { return <h1>Hello from Server</h1> } |
| // This is a Client Component 'use client'; export default function Button() { const handleClick = () => alert('Clicked!'); return <button onClick={handleClick}>Click me</button>; } |
| // app/page.jsx import { getCourses } from '@/lib/db'; import CourseList from '@/components/CourseList.client'; export default async function HomePage() { const courses = await getCourses(); return <CourseList courses={courses} />; } |
Also Read: