👋 Welcome back!
Today I thought of starting my first series about Next.js Fetching methods because many people (including me) don't understand them easily.
I will make these methods very easy for you to understand so that you don't have to be worried about how it works.
What is getStaticProps
?
In simple words, getStaticProps
is a method that can be exported from a page in Next.js which is simply used to get some data for further use.
For eg.
COPY
export default function MainPage(props) {
return (
<h1>{props.helloWorld}</h1>
);
}
export const getStaticProps = () => {
return {
props: {
helloWorld: 'Hello World'
}
}
}
We get back data in the form of props
, but we don't use getStaticProps
this way 👆.
If you have a database or you want to fetch some data from an API, you can use getStaticProps
. But only if that data is STATIC.
The getStaticProps
method runs at the build time, so whatever you write inside the method, is available to you statically. And it does not change over time because YOU NEVER FETCH THE DATA AGAIN.
Better example
Now let's take a better example to use getStaticProps
in Next.js and why you would want to use it instead of the normal fetching in React.
By using
getStaticProps
, the data is only fetched once and is READY TO USE without refetching.
Suppose you are building an app that has a list of people, and that list is always static. You want to show or use that list but you have them stored in the database or you are using an external API.
We will take an example of JSONPlaceholder API and we want to fetch the users from the API.
This is how the code will look like:
COPY
export default function MainPage({ people }) {
return (
<div>
{people.map(person => (
<>
<h1>{person.name}</h1>
<h2>Website: {person.website}</h2>
Email: <code>{person.email}</code>
</>
))}
</div>
);
};
export const getStaticProps = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const people = await response.json();
return {
props: {
people
}
};
};
Now when the app gets built using npm run build
, the data will be fetched at that point and it will be READY TO USE in your app.
So there is no need to fetch the data, show loading spinner, etc, etc. THE DATA IS ONLY FETCHED ONCE.
Thanks for reading!
I hope you liked it! Read the other posts of this series! Comment down your thoughts! There is always room for improvement so let me know your suggestions!
Connect with me on my YouTube channel and my Twitter 😉
Until next time, keeping awesome ✌️!