DEV Community

Ablomis
Ablomis

Posted on

Utilizing context to load data in Gatsby at runtime

If you are building a website on Gatsby it is very likely that you will want to load data from an external source, i.e. database.

There are two ways to do it with Gatsby:

  1. Load data i build time: the data is loaded during site build and then it is queried through Gatsby GraphQL. This approach works well for static data that doesn't change often.
  2. Load data at run-time: the data is loaded at runtime via APIs. This approach works well for dynamic data.

But even for this specific task there are multiple ways to do it. There are blogposts and that have specific components pull data from API whenever the component is displayed/mounted/.

Pros: the component data is alway up to date.

Cons: whenever user makes the component to unmount, for example when user clicks on another page within the website. If the API performance is not very good, for example.

Below we will take a look at how you can use contexts to load data through API on site load and make it accessible for all components.

Top comments (0)