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.
What Are React Server Components?
React Server Components or RSC are a feature of React introduced by the React team to allow certain components to be rendered on the server side. These components can only run on the server and do not send any Javascript to the browser which can be loaded on the client side.
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: Key Takeaways
- RSC can run only on the server and not in the browser.
- It can easily connect to databases in the infrastructure.
- The RSC uses async/await to fetch data, which is not possible in client components of React.
- The data is ready before the page is sent to the user and hence there is no loading or useEffect waiting for the same.
Normally, when using React we make use of useEffect() to fetch data after the page loads and manage all the loading states with the help of useState().
“React server components are a feature of React which allows you to execute some components on the server and reduce the client bundle size.” |
However, in React server components you can fetch data before the page even reaches the user and there is no use of useEffect and useState waiting. The page loads fast when it is pre-loaded with the required data. This makes your application simpler and faster.
Working of React Server Components
React Server Components can easily integrate with server side rendering into react applications. Based on user request a page containing server components can dynamically generate the HTML markup for these components and send it to the client with the initial page load preloaded.
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.
What is the use of React Server Components?
React Server Components solve issues that make our application faster and more optimised. You can fetch data and render them entirely on the server. This feature eliminates the need for client side rendering which improves the performance.
const data = await fetch(‘https://api.example.com/data’); |
The above data fetching is taking place on the server side. The RSC implements direct server side fetching where you can query a database or call APIs directly inside the component. It will eliminate the usage of useEffect or useState to fetch data.
With RSC we need smaller Javascript bundles as these components don’t send any Javascript to the browser. This ensures faster page loading and better performance on slow and unstable networks.
Also, we get better SEO and user experience as the content is visible to the search engine and the user sees the content immediately without waiting for the data to load. You can also use client and server components simultaneously.
What are the Limitations of React Server Components?
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.
- The RSC offers no interaction or features for client side interaction as it stays and renders only on the server. You cannot use methods like useState, useReducer, useEffect, and more in RSC.
- You cannot access browser APIs and features like window, document, localstorage, DOM manipulation and more. You cannot make interactive User Interface inside these server components.
- These React Server Components only support some frameworks such as Next.js, Remix, Custom React Servers. Hence, you cannot use these components in old react applications or plan to create react apps.
- It provides only limited support working with other libraries in React which might lead to compatibility issues with UI kits and other libraries.
- Debugging on the server console is harder where tracing errors might become more challenging as compared to the client side interactions.
- RSCs do not support frequent updates which will require a client side fetching for continuous updates.
How to Use React Server Components?
React Server components generally work based on three components i,e. Shared, server, and client components. Shared components are the components we generally use which can be executed both on client as well as server side.
While the server components can only execute on the server side. Client components can only execute only on the client side. The server components have .server.js extension and the client side components have .client.js extension. Shared components cannot have state or event listeners to make it possible you will need client components.
- You will need a framework that supports RSC such as Next.js, and more.
- By default all components have server components and to make it client components we can add “use client” at the top of the file.
// This is a Server Component by default
export default function Page() { return <h1>Hello from Server</h1> } |
To make it a client component, we can add “use client” at the top of the file.
// This is a Client Component
‘use client’; export default function Button() { const handleClick = () => alert(‘Clicked!’); return <button onClick={handleClick}>Click me</button>; } |
- We have to fetch data directly in a server component using an asynchronous method using “async/await.
// 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} />; } |
- You can use client components to add interactivity in your application.
Benefits of using React Server Components
There are many benefits of React Server Components which renders everything on the server side.
Faster Loading
Smaller javascript bundles in RSC there are no javascript sent to the browser. This makes the page faster with better performance even on slower and unstable networks.
Improved Performance
React server components significantly reduces the load time of web applications which provides better user experience and smoother load time.
Better Security
As React Server Components are on the server side this safeguard the sensitive data from potential security and integrity threats such as Cross side Scripting (XSS) attacks, and more.
Improved SEO
Search Engine Optimisation is better with server side React Server Components which can easily index contents on the search engine and make content visible instantly and users do not have to wait for loading. This also help boost search engine rankings on server.
No Event Effects or Client Side State Needed
The server components do not use event information like useState, useEffect, and more to fetch data. You can write simpler and cleaner components. You can have direct access to server side resources such as database, file system, authentication logic, and more.
Also Read:
- What Is Frontend Development? Complete Explanation
- What Is a Management Information System (MIS) -12 Steps Effective Guide
- Flexbox vs Grid in CSS: 7 Clear Ways to Decide When to Use What
- 15 Outstanding HTML5 Semantic Elements Explained for Beginners and Professionals
Learn Full Stack Web Development With PW Skills
Start making your shining career in Full Stack Web Development with in-depth learning and hands on experience in PW Skills Full Stack Web Development Course. This course will help you learn industry technologies, real world applications, hands on experience, and more to become a full stack web developer.
Learn in-depth concepts of frontend development, backend development, and more. Get complete doubt support with SME sessions. Get career guidance and interview preparation from our dedicated mentors. After you complete the course you will get a certificate of completion from PW Skills. Enhance your portfolio and become job ready with pwskills.com
Perks of Full Stack Development Course
- You will learn how to build a strong job portfolio with in demand skills and experiences in web development.
- Learn from industry led live sessions every weekend including pre-recorded modules.
- Get a complete career assistance with opportunities and a platform to showcase your knowledge and experience.
- Master Frontend frameworks, backend frameworks, full stack web development along with real time coding practice sheets, module assignments and more.
- Build a strong concept using practice exercises and module level assignments within this course.
- Get industry recognised certificates from PW Skills and discover a wide range of opportunities in the design field.
- Get a complete hands on training with our real world capstone projects within this course.
React Server Components FAQs
Q1. What are React Server Components?
Ans: React Server Components or RSC are a feature of React introduced by the React team to allow certain components to be rendered on the server side.
Q2. Is React Server Component rendered on client side?
Ans: React Server Components (RSC) is rendered on the server side with minimal client JS, faster loading where you do not need to use client side state or effects needed.
Q3. Does RSC have effect on SEO?
Ans: The React Server Components makes faster loading which improves page speed, Search Engine Optimisation (SEO) and better user experience on slow networks.
Q4. What are the server components in React?
Ans: Server side components are the components in react which first render on the sever before it is sent to the client side. This help developers to write the UI which can be rendered and cached on the server helping in faster execution.
Q5. Are React Server components worth it?
Ans: React server components is a remarkable feature which is used to solve the long existing problem of overloading of Javscript, lags in loading, improved SEO, and more. They allow us to compose server side and client code without switching between different models.