Anyone who has used apollo-client as a state manager knows it is a fantastic but bloated tool.

Changing an entry in a list of todos can be an uncomfortable task with a lot of boilerplate code — like the twenty-something lines of code below:

Expecting to reduce the effort on jobs like these, I’ve been thinking of ways to make them a little simpler and more straightforward.

The question I’ve tried to answer recently was: is there a way to make this task as simple as using the hook useState ?

And yes, it is possible. In the next few lines, I will share the answer I found.

useAppState

The use of hooks is a powerful resource for structuring the behavior of our applications.

It’s amazing how many lines of code I’ve been saving by encapsulating the behavior of my components in these functions.

Since I adopted useState for the local state management of my components, I've been looking for ways to do the same for a broader scope.

For this purpose, I wrote the package useAppState .

With it, you can modify a cached state to, for example, open and close a floating menu.

We have above two isolated components that share the same state isOpen . At the same time, the hook provides a setter that allows the change of this value.

Variables

You may assign variables to your queries as follows:

We can illustrate this with an example involving two counters:

The components of this example are structured as follows.

The way the display Counter and its controller AddOneButton are organized internally is shown below:

The hook useCount encapsulates the behavior of our components as well as the details of interacting with our package, as detailed below:

Note the use of variables in the call of useAppState . It is the assignment of different values to label that gives independence to the states of the counters A and B .

Updating queries without @client

Although the above examples focus on updating queries with the @client directive, useAppState can be used to update any cached data.

Any list fetched from the server could be updated locally like this.

Under the hood

Internally, useAppState uses the hook useQuery , launched in August 2019, to reactively access the state of the query . At the same time, a call to client.writeQuery is encapsulated by its setter.

The creation of this hook involved approximately 40 lines and is available at the link.

I hope this little utility allows you to write a little less boilerplate code :)

Acknowledgment

Thank you, @finnfrotscher and @aishablake, for your precious feedback.