Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS: getInitialProps method

Working with NextJS and saw an example of a page:

class IndexPage extends Component {
  static async getInitialProps(context) {
    return {};
  }
  render() {
    return <div>hello world</div>;
  }
}
export default withRouter(IndexPage);

What exactly does the getInitialProps method in NextJS?

like image 219
Willem van der Veen Avatar asked Nov 28 '22 21:11

Willem van der Veen


1 Answers

getInitialProps is usually an async function which is good for asynchronous operations at the server and then it passes data to the page as props.

It can run both on the server and on the browser(if you use Link for example).

My conclusion would be to use getInitialProps to fetch data when your component acts as a Page, and you want to provide the data as Props.

Docs: https://nextjs.org/learn/basics/fetching-data-for-pages

like image 150
Joan Albert Avatar answered Dec 10 '22 08:12

Joan Albert