Blog>
Snippets

Utilizing getStaticProps for Component-Level Data

Example that shows how to use getStaticProps at the page level to fetch data at build time and pass it down to child components.
import { useState, useEffect } from 'react';

export default function PageComponent({ initialData }) {
  // Use useState to manage the data within the component.
  const [data, setData] = useState(initialData);

  // UseEffect is not necessary for static data, but you can use it for asynchronous operations
  // useEffect(() => {
  //   async function fetchData() {
  //     // Your fetch logic here
  //   }
  //   fetchData();
  // }, []);

  return (
    <div>
      <ChildComponent data={data} />
    </div>
  );
}

function ChildComponent({ data }) {
  // This child component receives the static data as props
  return (
    <div>
      {/* Data rendering logic goes here */}
      {data.map(item => (
        <p key={item.id}>{item.title}</p>
      ))}
    </div>
  );
}
This is a React functional component using static generation with getStaticProps. The initial data fetched at build time is passed to the child component as props. The data is then rendered in the child component.
export async function getStaticProps() {
  // Fetch data at build time. This can be from a CMS, API, FileSystem, etc.
  const response = await fetch('https://myapi.com/data');
  const data = await response.json();

  // Pass the data to the page via props
  return { props: { initialData: data } };
}
getStaticProps function fetches data at build time which will be passed to the page component as initialData. This allows the data to be used when pre-rendering the page server-side.