clearStore() vs resetStore()

I’m wondering what the difference is between clearStore() vs resetStore().

According to the Apollo docs:

The easiest way to ensure that the UI and store state reflects the current user’s permissions is to call client.resetStore() after your login or logout process has completed. This will cause the store to be cleared and all active queries to be refetched. If you just want the store to be cleared and don’t want to refetch active queries, use client.clearStore() instead.

It mentions resetStore() will “cause the store to be cleared and all active queries to be refetched.” What exactly is an active query, and why would it need to be refetched if you’re trying to clear that cache?

Thank you!

1 Like

When you fetch data with Apollo Client using either watchQuery or useQuery (which uses watchQuery behind the scenes), you’re telling Apollo Client to keep an eye on the cache for future changes to the data that resulted from your query, and depending on your configured fetch policy, refetch data from your backend if the query can’t be satisfied from the cache. If any changes happen to the cached data, and your query is still “active” (it’s still watching the cache for changes), your application will be notified of those changes. Apollo Client queries will continue to watch the cache / refetch as needed until they’re told to stop (which can be done manually or automatically - e.g. when a component using useQuery is unmounted).

resetStore can come in handy when you want to fully clear out the cache, and have all of the active queries re-run themselves, to bring the cache back into a fresh state. E.g. maybe your application stores data in the cache that should be available to anyone using the application, but also stores data in the cache that is specific to a user; logging that user out should remove their specific data, but refreshing things to keep the shared data in place is useful to get things ready for the next user. Picture an application that dynamically renders its navigation based on the result of querying a GraphQL backend to know which menu items to show. If this navigation is going to be same for everybody, but we want to clear out user specific parts of the cache, calling resetStore on logout could be a good choice to make sure the active navigation query is rerun before someone else logs in.

clearStore can come in handy when you want to wipe the entire cache, without re-running any of the active queries.

3 Likes