I have been using Apollo Client for a few years but have never tried it as a local state management tool. I like the approach because of the following:

  • If you already use GraphQL and Apollo Client you can avoid having an additional tool for state management like Redux. That reduces the size of your JavaScript bundle and the amount of boilerplate code.
  • Using the same approach to querying data whether it comes from the backend or local state.

Recently I decided to give it a try but had little knowledge of how it works and questions like:

  • Where exactly is the local state stored when using Apollo?
  • Why is it mixed up with Apollo cache?
  • Why is Query syntax used for getting data, but not Mutation syntax for changing it?

In the beginning, I found many articles that explained the topic using deprecated local resolvers API that only increased my confusion. This article was born after a few days of my attempts to put local state management pieces together in the correct way.

Apollo local state and how it is stored

Apollo Client is a state management library that enables you to manage both local and server data. Speaking about local data, it doesn’t make you coupled to the way you store it. You can decide whether to use localStorageindexedDB or Apollo provided storage. The only thing that is explicitly defined is how you query the data: you should use a single GraphQL API for both local and server data. In other words, to get local state data, you need to use Query.

Image for post

Apollo provides you with built-in storage mechanisms like Apollo InMemoryCache and Reactive variables.

We will take a look at and try them both out.

#react #apollo-cache #apollo-client #state-management #reactive-variables

Storing local data with Apollo Client
3.50 GEEK