Subscribing to local variables from Apollo client with reactive variables

Subscribing to local variables from Apollo client with reactive variables

·

2 min read

Quick Summary

While using local variables in our application from the apollo client, we can read and update the variables but any changes to the values of these variables do not trigger our component to re-render since we are only "reading" the value from the cache. In this post, we will discuss how to make our components re-render when the variables are updated.

Get started

In the last post, we learned about how to get started with using the variables in the apollo client, from defining to updating them. In case you haven't already, check out the post here.

It works well if we are always manually triggering the variables to read their values and our components' UI state does not depend upon these variables. But sometimes we need these variables to cause a re-render or update in our component similar to a react state or props does.

While using redux, we achieve this by subscribing to the redux store which is usually the default way to access the data from redux.

Apollo client v3 provides a solution for this with reactive variables. To make a local variable reactive, we need to use the useReactiveVar hook from apollo client.

Let's take an example of a todo list, we are using local variable to store and read (render) the todo list items. We will make the todo list variable reactive, to make the list re-render and update according to the todo list variable's current values.

import { useReactiveVar } from '@apollo/client'
import { todoList } from '../cache'

// todoList is a regular local variable in apollo client
// we use useReactiveVar to make it reactive and use it for our Todo list
const reactiveTodoList = useReactiveVar(todoList);

Now we can use reactiveTodoList to render the todo list items and it will trigger the component to re-render as new todos are added to the list.

Check the demo here. (code)

Conclusion

We learned how to subscribe to the changes to a local variable in the apollo client using useReactiveVar. With this, we are ready to use Apollo client as the state management solution for our application alongside helping to perform GraphQL operations.