The term is self-explanatory. Prefetching is a way to make your app's UI feel instantaneous by anticipating when a user will require data to be loaded. One way I use this in my Teachery app is when a user hovers over the More pagination button, it will prefetch the next set of data, saving the user a click and a second or two of time. These small prefetching techniques add up, providing a snappy performance users will praise.
Here's an example of an onMouseOver event that triggers a client query to prefetch information.
const Query = () => {
const { loading, error, data, client } = useQuery<GetPostsData, GetPostsVars>(
GET_POSTS,
{ variables: { options: { paginate: { page: 1, limit: 3 } } } }
);
return (
<div>
{loading ? (
<p>Loading...</p>
) : error ? (
<p>Error! `{error.message}</p>
) : (
<div>
{data &&
data.posts.data.map((post) => <Post key={post.id} post={post} />)}
</div>
)}
<>
<button
type="button"
onMouseOver={() =>
console.log(
client.query({
query: GET_POSTS,
variables: { options: { paginate: { page: 2, limit: 3 } } },
})
)
}
>
Show
</button>
</>
</div>
);
};
Another pattern used is optimistic UI which simulates the result of an Apollo mutation or update before receiving a response from the server. After the response is received, the optimistic response is replaced with the actual result. This pattern provides a way to make your UI respond much faster, and is useful in cases where a user edits certain items that are likely to not change after the server response is received. For example, we could use optimistic on a like/unlike button, or editing the title of an item (as used in my Teachery project).
const [updateCard, { loading, error }] = useMutation(UPDATE_CARD, {
optimisticResponse: {
__typename: "Mutation",
updateCard: {
id: id,
__typename: "",
front: front,
back: back,
pictureName: pictureName,
pictureUrl: pictureUrl,
},
},