Client-side rendering (CSR) in Next.js involves loading and rendering components on the client side, after the initial HTML has been generated on the server. This allows for a faster initial page load and enables a more dynamic user experience. Here's a step-by-step guide on how to implement client-side rendering in Next.js:
Install Next.js: Make sure you have Next.js installed in your project. If not, you can install it using:
bashnpm install next react react-dom
Create a Next.js project: Create a new Next.js project using the following command:
bashnpx create-next-app my-next-app
cd my-next-app
Create a new page:
Inside the pages
directory, create a new file for the page where you want to implement client-side rendering. For example, create a file named csr-page.js
.
Implement CSR:
In the page component file (csr-page.js
), use the useEffect
hook from React to fetch data and update the component on the client side. Here's an example:
jsximport { useEffect, useState } from 'react';
const CSRPage = () => {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data on the client side
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []); // Empty dependency array ensures the effect runs only once
return (
<div>
<h1>Client-Side Rendering Page</h1>
{data && <p>Data: {data}</p>}
</div>
);
};
export default CSRPage;
In this example, data is fetched on the client side using fetch
within the useEffect
hook. The component updates when the data is available.
Update your next.config.js
:
Ensure that your next.config.js
file has the following configuration to enable client-side rendering:
jsmodule.exports = {
reactStrictMode: true,
};
Run the development server: Start your Next.js development server:
bashnpm run dev
Open your browser and go to http://localhost:3000/csr-page (replace csr-page
with the actual file name or route you created).
Now, when you navigate to the specified page, the data will be fetched and rendered on the client side. This is a basic example, and you can customize it based on your specific requirements. Remember that client-side rendering is particularly useful for pages where you want to load data or content dynamically after the initial page load.