Welcome to our comprehensive guide on React JS! Today, we'll dive deep into getServerSideProps. This powerful feature is a part of Next.js, a popular React framework for server-side rendering. Let's get started!
getServerSideProps?getServerSideProps is a Next.js function that fetches data on the server-side before the page is rendered. It helps to optimize performance, especially for dynamic data.
When should you use getServerSideProps? Use it when you need to fetch data on the server-side before rendering the page. It's ideal for SEO and improving performance.
Remember, getServerSideProps only works with Next.js. If you're using a plain React setup, you won't find this function.
First, let's set up a new Next.js project. Run the following command in your terminal:
npx create-next-app my-appNow, navigate to your project directory:
cd my-appNext, we'll create a dynamic page that uses getServerSideProps. In the pages directory, create a new file called [id].js.
touch pages/[id].jsReplace the content of pages/[id].js with the following:
import React from 'react';
export async function getServerSideProps(context) {
const id = context.params.id;
const res = await fetch(`https://api.example.com/data/${id}`);
const data = await res.json();
return {
props: { data }, // will be passed to the page component as props
};
}
function Page({ data }) {
return (
<div>
<h1>Page with id: {data.id}</h1>
<p>Data: {JSON.stringify(data)}</p>
</div>
);
}
export default Page;Here's what's happening:
getServerSideProps is an async function that accepts a context object, which contains information about the current request.id from the context.params.fetch.props.Page component as props.getServerSideProps only runs on the server-side, so you can't use React hooks like useState or useEffect inside this function.
What does `getServerSideProps` do in Next.js?
Stay tuned for more on React JS! We'll cover more advanced topics and provide more practical examples. Happy learning! š
š Note: This tutorial is just a starting point. As you progress, explore more features of getServerSideProps like handling errors, updating data, and more!
Next Lesson: Using getInitialProps and Comparing it with getServerSideProps