Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get initial data from api before app loaded in next.js

Tags:

next.js

I want to load some data from api before application rendered.

Yes, I know we can do it in getInitialProps method of component, but I don't want load it on each component loading, I need make only 1 api call and make accessible retrieved data among all components. What is the easiest way to do it?

like image 409
Zhassulan Nurushev Avatar asked Dec 09 '25 05:12

Zhassulan Nurushev


1 Answers

Yes, I know we can do it in getInitialProps method of component

I think this may be where your confusion is coming from. The getInitialProps method is for page loads. Not for individual component loads.

I need make only 1 api call and make accessible retrieved data among all components.

There are a couple of ways to do this.

If you want to take advantage of SSR

Use getInitalProps for the page load and then pass the props down into sub components as you would in normal react application.

If you just want to stick to React

Make a higher level component that contains all of the sub components that need the api data. Call the api in the ComponentDidMount method or you could use React Hooks. From the higher level component again pass the data via props as you would in a normal react application.

Either way you are limiting the number of times you make the api call. That way you aren't hitting the endpoint each time the DOM re-renders each and every component.

Both the Next.js Learn and React Docs are excellent - I'm there all the time!

like image 147
Andrew Bass Avatar answered Dec 11 '25 10:12

Andrew Bass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!