DEV Community

Syed Muhammad Ali Raza
Syed Muhammad Ali Raza

Posted on

Next js Data Fetch

Introduction:

Next.js, the popular React framework for building web applications, provides powerful features for data retrieval, allowing developers to create dynamic and responsive user experiences.

1. Creating a Static Site (SSG):

Static site generation is a key feature of Next.js, which previews pages as they are built. This approach is ideal for content that doesn't change often, loads faster, and improves SEO performance. Next.js supports retrieving data using methods like "getStaticProps" and "getStaticPaths" during the build process.

  • "getStaticProps": This function allows you to get static props and pass them as props to your component. The external API is useful for retrieving data from a database or local file system. By pre-rendering the page and the retrieved data, Next.js generates highly optimized static HTML files.

  • "getStaticPaths": Used together with "getStaticProps" for dynamic paths, "getStaticPaths" determines which paths Next.js should pre-render based on received paths. This allows you to create dynamic pages with optimal performance.

2. Server Side Display (SSR):

Server-side rendering in Next.js involves taking data in each request, adjusting to content that changes frequently or requires personal data. Next.js provides "getServerSideProps", a method to get server-side information before rendering the page.

  • "getServerSideProps": With this function, data is obtained and passed as a prop to the component in each request. This ensures that the content of the site is always up-to-date, making SSR ideal for sites that require real-time data, user-specific content, and authentication.

3. Static update (ISR):

Incremental static refresh is a feature introduced in Next.js 9.5 that combines the benefits of SSG with the ability to refresh static content without rebuilding the entire page. ISR allows you to refresh static pages on demand, ensuring smooth updates while maintaining high performance.

  • ISR with "refresh": By specifying the refresh interval, you can get background information about how often Next.js refreshes the static page. It minimizes the need for manual rebuilds and ensures your content is up-to-date.

4. Collection of Information by Customers:

Next.js also supports client-side data collection using popular libraries such as fetch, axios or SWR (Stale-while-Revalidate). Client-side data retrieval is useful for interactive components, user-driven updates, and scenarios where pre-rendering is not possible.

// pages/index.js

import 'reaction';
import axios from 'axios';
import link from 'next/link';

// Static Site Generation (SSG) - Get data during construction
export async function getStaticProps()
  // Get data from external API
  const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
  const records = res.data;

  // Pass the returned data as an advertisement
  return {
    advertisement: {
      records,
    },
  };
}

const Home = ( { entry } ) => {
  return (
    <div>
      <h1>Recent post</h1>
      <ul>
        { post.map (post => (
          <li key={post.id}>
            <Link href={`/posts/${post.id}`}> link
              <a>{post.title}</a>
            </link>
          </li>
        ))}
      </ul>
    </div>
  );
};

expor default Home
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We get information from the JSONPlaceholder API during construction using "getStaticProps".
  • The obtained data (list of records) is transferred to the "Home" component as an advertisement.
  • We provide a list of articles and links to each article's detail page.

For Server-Side Rendering (SSR), you replace "getStaticProps" with "getServerSideProps" and data collection will be done on every request instead of build time.

For incremental static refresh (ISR), you can specify how often the page should be refreshed with new data by combining "getStaticProps" with the "recheck" option.

For client-side data retrieval, you can use libraries like axios, fetch, or SWR in your component to retrieve client-side data. Here is a basic example using axios:

import Reaction from Reaction { useState, useEffect;
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState ([]);

  useEffect (() => {
    const fetchData = async() => {
      const result = await axios.get('https://api.example.com/data');
      setData(result.data);
    };

    fetchData();
  }, []);

  return (
    <div>
      <h2> Information: </h2>
      <ul>
        { data.map(element => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

The results:

Next.js offers several data collection methods that allow developers to choose the most appropriate approach based on their application requirements. Whether it's creating static sites for fast performance, server-side rendering for dynamic content, or incremental static updates for regular updates, Next.js allows developers to easily build high-performance web applications. By understanding and utilizing these data acquisition methods, developers can create engaging and effective user experiences while optimizing performance and scalability.

Top comments (0)