Data fetching in Next.js
Fetching data from an API is a common task in web development. In this article, we will discuss how to fetch data from an API in Next.js using both server-side and client-side rendering.
Server Side data fetching in Next.js
Next.js allows you to fetch data on the server side and pre-render the page before sending it to the client. This can be useful for SEO and performance reasons. To fetch data on the server side in Next.js, you can use the getServerSideProps method. Here is an example:
const fetchData = async () => { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; } export async function getServerSideProps() { return fetchData(); }
Client Side data fetching in Next.js
If you want to fetch data on the client side, you can use the useEffect hook in a functional component or the componentDidMount lifecycle method in a class component. Here is an example of fetching data on the client side in a functional component:
import { useEffect, useState } from 'react'; const fetchData = async () => { const res = await fetch('https://api.example.com/data'); const data = await res.json(); setData(data); } const [data, setData] = useState(null); useEffect(() => { fetchData(); }, []);
SWR for data fetching in Next.js
SWR is a React hook for data fetching that is optimized for server rendered applications. It provides many features such as caching, revalidation, loading state management, and error handling. To use SWR in Next.js, you can install the swr package and use it in your components. Here is an example:
import useSWR from 'swr'; const fetcher = (url) => fetch(url).then((res) => res.json()); const { data, error } = useSWR('https://api.example.com/data', fetcher); if (error) returnError fetching data; if (!data) returnLoading...; return{data};
By following these methods, you can effectively fetch data from an API in Next.js for server-side and client-side rendering, as well as use the SWR hook for optimized data fetching. Happy coding!