Next Js getStaticProps


Posted 2 months ago by Ryan Dhungel

Category: Next JS SSR Web Development

Viewed 398 times

Estimated read time: 2 minutes

Understanding Next.js static method called getStaticProps

 

  • Next.js getStaticProps can be used to server render data that you get from api request.
  • The data required to render page is available at build time.
  • This is specially useful when you want to server render the data you receive from API request but on build time.
  • It will be faster than completly server rendered pages that uses getInitialProps method.
  • It is suitable for landing page or home page where you don't want to wait for server response but still want to show the content that once requires server request (will happen in build time).

Here is an example of using getStaticProps.

import Head from "next/head";
import Layout from "../components/Layout";
import axios from "axios";

const HomePage = ({ data }) => {
  return (
    <Layout>
      <div>Welcome to Next.js!</div>
      {data.map((d) => (
        <p key={d.id}>{d.title}</p>
      ))}
    </Layout>
  );
};

export const getStaticProps = async () => {
  const { data } = await axios.get(
    `https://jsonplaceholder.typicode.com/todos`
  );
  // console.log(data);
  return {
    props: {
      data,
    },
  };
};

export default HomePage;