Improving performance in Apollo Client
Redirecting to cached data
In some cases, a query might request data that's already present in the Apollo Client cache thanks to a different query that already ran. For example, your UI might have both a list view and a detail view with queries that fetch the same fields from a particular object.
In cases like these, you can avoid sending your server a followup query that fetches identical data. To learn how, see Cache redirects.
Prefetching data
Prefetching involves executing queries for data before that data needs to be rendered. It helps your application's UI feel more responsive to the user.
Most of the time, prefetching involves querying for data as soon as you can guess that a user will probably need it.
For example, this code snippet calls client.query
to execute a query when the user hovers over a particular link (to a page that uses the data returned by the query):
Click to expand
1function Feed() {
2 const { loading, error, data, client } = useQuery(GET_DOGS);
3
4 let content;
5 if (loading) {
6 content = <Fetching />;
7 } else if (error) {
8 content = <Error />;
9 } else {
10 content = (
11 <DogList
12 data={data.dogs}
13 renderRow={(type, data) => (
14 <Link
15 to={{
16 pathname: `/${data.breed}/${data.id}`,
17 state: { id: data.id }
18 }}
19 onMouseOver={() =>
20 client.query({
21 query: GET_DOG,
22 variables: { breed: data.breed }
23 })
24 }
25 style={{ textDecoration: "none" }}
26 >
27 <Dog {...data} url={data.displayImage} />
28 </Link>
29 )}
30 />
31 );
32 }
33
34 return (
35 <View style={styles.container}>
36 <Header />
37 {content}
38 </View>
39 );
40}
When the GET_DOG
query completes, its result is stored in the Apollo Client cache. This means that if the user then clicks the link, the dog's detail page can immediately populate that data from the cache, which feels instantaneous to the user.
In addition to a mouse hover, here are some other suggestions for situations when prefetching can be helpful:
During a multi-step flow (such as a wizard), you can preload each next step's data during each current step.
If your app's analytics indicate a frequent transition between two particular views, you can use prefetching to optimize for that path.
If a region of a page has multiple tabs or slides (such as a carousel), you can preload data for some or all of them to make transitions feel snappier.
A special form of prefetching is store hydration from the server, so you might also consider hydrating more data than is actually needed for the first page load to make other interactions faster.
Feel free to submit a PR with suggestions for other preloading opportunities!