WARNING
50% of the accepted answer is wrong. Here's why. Let me split my answer in two sections:
Part 1:
GetInitialProps is usually an async function which is good for
asynchronous operations at the server and passes data to the page as
props.
In Next.js it always runs at the server, if the page is called using Link then it is only called at the client side
Wrong, GetInitialProps get executed on both the server and browser (remember the goal of Next.js is to make universal JavaScript). Here is what the documentation says:
With that, we can fetch data for a given page via a remote data source
and pass it as props to our page. We can write our getInitialProps to
work on both server and the client. So, Next.js can use it on both
client and server.
Part 2:
The second section is to answer the actual question more accurately. It's clear that the OP got confused between ComponentDidMount and ComponentWillMount. Because in the Next.js case it makes more sense to compare GetInitialProps vs. ComponentDidMount as they both able to make Async call to fetch data, and they also both allow rendering afterwards (which is not possible in the case of ComponentWillMount).
In any case you use one or another, there are a few differences:
GetInitialProps: is provided by Next.js and it is not always triggered, so be careful with that. It happens when you wrap one component inside another. If the parent component has GetInitialProps, the child's GetInitialProps will never be triggered. See this thread for more information.
ComponentDidMount: is React implementation and it's always triggered on the browser.
You might ask: 'so when should I use this or that?'. Actually it is very confusing and at the same time very simple. Here is a rule of thumb:
- Use GetInitialProps to fetch data when your component acts as a page, and you want to provide the data as Props.
- Use ComponentDidMount on children components (that are not pages) or when you want to update the state upon an Ajax call.