Reactive variables are useless

The Apollo docs describes reactive variables as “a useful mechanism for storing local state” and as a state management solution, so I tried to use them to store some data but the data won’t persist when the page is refreshed or while doing page navigation.
So what’s the point of using them? How is a reactive variable better than useState?
Am I misunderstanding something?

@luisadrian there are several differences between reactive variables and useState; here are a couple main ones:

  • Reactive variable state isn’t tied to a component, or even to React for that matter. Reactive variables are an Apollo Client state management solution that gives you a way to store application state at any level of your application.
  • When you tie reactive variables into queries in Apollo Client, using @client and field policies for example, every time you update the value of your reactive variable anywhere in your application, all queries that are using it elsewhere will automatically re-run. The Storing local state in reactive variables section of the docs helps explain this.

Just like React, Apollo Client does not persist state between page reloads (but depending on how you’re handling page navigation - ie. not reloading - it will). If you want to persist state between reloads, we suggest using the Apollo Client cache and a solution like apollo3-cache-persist. At some point in the future we’re going to build persistence into Apollo Client, but we’re not quite there yet.

2 Likes

Hi @hwillson !

Sorry if this comment is off-topic to the OP’s post; however, I am trying to figure out the proper way to use reactive variables as my state management solution.

Essentially, all I want to do is define some state that I can then access in multiple components in the tree hierarchy without prop drilling and causing unnecessary re-renders. It seems like the simplest solution for this is to define my variable and use the useReactiveVar hook, right? No need to introduce type policies or including my variable in a query. I just want to make sure I am understanding their purpose correctly so that I don’t set myself up for failure down the road.

On top of that, how can I co-locate my reactive variables so that they’re only accessible within a subset of components similar to how the Provider/Consumer pattern works? This isn’t as important but it would be nice to know if we can scope variables in some way!