Intro To Optimizing React Application Performance using React Apollo Client
Diving into solutions around React performance optimization is a large topic. I’d like to address the topic of optimizing performance based on controlling and reducing expensive client network requests by exploring the solutions offered by the React Apollo Client library.
From the documentation itself the solutions Apollo addresses:
- State management of local and remote data with GraphQL
- Fetch application data
- Modify application data
- Cache data
One important aspect that I appreciate about Apollo Client compared to other client HTTP libraries like Axios, is increased control over how applications handle network requests. Although Apollo offers more, I want to address 3 approaches to optimize client side network requests using Apollo:
- Controlled fetch operations with useQuery
- Component event listeners and useLazyQuery
- Fine tuned data caching with fetchPolicy
Imagine you have a component that needs to query a very expensive network request in order to render the correct data. Ideally, you may only want the component to re-fetch that data if:
Case 1: The request itself has changed
Case 2: The user as initiated some action
Case 3: The data response has changed
If you’re a front end engineer, you’ve ran into this problem. Here are ways to use Apollo to address this optimization.
Case 1: If a fetch should only occur when a request has changed, try a useQuery with a skip variable. Apollo allows us to listen for “variable” updates within our component that can be passed as arguments to update the body, headers, query parameters, etc. in our fetch request. It also gives us a skip variable that allows us to skip the fetch based on controlled variable conditions.
Case 2: If a fetch does not need to occur every time the component mounts, and is only needed based on a user interaction, try a useLazyQuery.
Case 3: If a fetch only needs to occur if something in the response data has changed, try implementing a fetchPolicy. By default, the useQuery hook checks the Apollo Client cache to see if all the data you requested is already available locally. If all data is available locally, useQuery returns that data and doesn't query your GraphQL server. There are a variety of fetch policies to support the right cache operations. For example you can use a cache-only policy which queries against the cache and never queries the server.
This article only suggests a few of the options available at the component level for Apollo fetch queries. Read more here.