Client-side Data Fetching with useSWR and fetch
Client-side Data Fetching involves fetching data directly from the client-side, after the initial HTML has been loaded. This approach is suitable for parts of the application that require frequent data updates without changing the entire page structure.
How it Works:
- In Next.js, you can use libraries like SWR or native JavaScript fetch to fetch data on the client-side.
- SWR is a popular library that handles data fetching, caching, and revalidating data automatically.
- When data is fetched on the client-side, it can be dynamically updated without requiring a full page reload.
Use Cases:
- Real-time updates (e.g., live chat messages, stock prices).
- Interactive components that fetch data based on user interactions (e.g., search results, infinite scrolling).
- Parts of the page that don’t need SEO optimization or initial server-side rendering.
Syntax (useSWR):
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then((res) => res.json());
export default function Profile() {
const { data, error } = useSWR('/api/user', fetcher);
if (error) return <div>Error loading data</div>;
if (!data) return <div>Loading...</div>;
return <div>{JSON.stringify(data)}</div>;
}
Example: Below is an example of fetching data using useSWR in NextJS App
// index.js
import { useEffect, useState } from 'react';
export default function Profile() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/user')
.then((res) => res.json())
.then((data) => setData(data))
.catch((error) => console.error('Error fetching data:', error));
}, []);
if (!data) return <div>Loading...</div>;
return <div>{JSON.stringify(data)}</div>;
}
Output:
How to Fetch data faster in Next.js?
NextJS, a popular React framework provides various approaches to fetch data efficiently. Optimizing data fetching can significantly improve the performance and user experience of your NextJS applications.
We will discuss different approaches to Fetch data faster in NextJS:
Table of Content
- Static Generation using getStaticProps
- Server-side Rendering using getServerSideProps
- Client-side Data Fetching with useSWR and fetch