Fetch less data

Less is more. Yeah, really. One of the great benefits of GraphQL is that you get exactly the data you ask for, nothing else. This makes it easy to avoid over-fetching, which is when you get much more data than you actually use.

When you initialize your shop, you will find a series of .gql files within your repository. Most of the queries run by Flight makes use of these .gql files. To optimize performance, you should make sure that these queries and fragments only contain the fields that you are actually using.

This means that if there's functionality on the product page that you're not using, you should remove it both from the React tree, but also from the .gql query that is being run.

Removing unused fields will improve performance in many ways:

  • Reducing the amount of data in the memory cache of the browser, leading to less memory usage
  • Reducing the amount of data sent over the wire, leading to less data usage
  • Reducing the amount of data processing done on the server, leading to faster response from the server
  • Reducing the complexity of the queries sent to the StoreAPI, leading to faster response from the API

Avoid waterfalls when possible

Another pitfall when fetching data this way is that you can create request waterfalls. For example, if you have a query that is run only on the product page, you should be aware of that when the client lands on a route, it first goes through the DynamicRoute component, which runs the routeQuery. When that data is resolved, the app now knows that it should render a product page, and then finds that there's another query that needs to be run before it can finally render the app. It can be expressed as follows:

  1. Query the StoreAPI to do the route lookup (150 ms)
  2. Query the StoreAPI to run the product page query (150 ms)
  3. Render the app on the server (50 ms)

Total time: 350 ms

If you could write your code in a different way, e.g. making sure that the data for the product page is fetched in parallell with the route lookup you would end up with the following:

  1. Query the StoreAPI to do the route lookup and query the StoreAPI to run the product page query (150 ms)
  2. Render the app on the server (50 ms)

Total time: 180 ms

While this is a theoretical scenario, these types of waterfalls are quite common when you're not aware of this problem. Imagine how another level of waterfall would add to this and we're soon at quite slow response times.

Copyright © Norce 2023. All right reserved.