Jan 18, 2024

Harnessing Apollo Client 3's Reactive Variables for Local State Management

Explore the power of Apollo Client 3's Reactive Variables for seamless local state management in our latest blog.

Author

Simranjit SinghSimranjit SinghSenior Software Engineer - II
Harnessing Apollo Client 3's Reactive Variables for Local State Management

Apollo Client 3 has introduced a powerful feature called reactive variables, providing a flexible mechanism for managing local state independent of the Apollo Client cache. This article explores the significance of these variables, their creation, manipulation, and utilization through the useReactiveVar hook.


Understanding Reactive Variables

Reactive variables are distinct from the cache, allowing storage of diverse data types and structures without reliance on GraphQL syntax. Reactive variables offer a significant advantage through their innate ability to detect changes effortlessly via the useReactiveVar hook. When a reactive variable's value undergoes modification, Apollo Client seamlessly recognises this alteration. This allows for seamless, real-time updates to our app’s UI, without the need for manual intervention.


Creating Reactive Variables

Let us explore how to create and utilize reactive variables.

import { makeVar } from '@apollo/client';
import { CartItem, ViewMode } from '@types';

// Creating a reactive variable
const initialCartItems = [];
export const cartItemsVar = makeVar<CartItem[]>(initialCartItems);

Utilizing Reactive Variables

Reading the value:

const cartItems = cartItemsVar();

Modifying the value:

cartItemsVar([...cartItems, newItem]);


Reacting

useReactiveVar

As the name suggests, reactive variables can trigger reactive changes in your application. Whenever you modify the value of a reactive variable, queries that depend on that variable refresh, and your application's UI updates accordingly.

The useReactiveVar hook can be used to read from a reactive variable in a way that allows the React component to re-render if/when the variable is next updated.

import { makeVar, useReactiveVar } from "@apollo/client";
import { cartItemsVar } from '@reactiveVars/cart';

export const Cart = () => {
  const cartItems = useReactiveVar(cartItemsVar);
  // ...


Comparing Reactive Variables with Redux

Benefits of Reactive Variables over Redux

  1. Reduced Boilerplate: Reactive variables eliminate the need for multiple actions, reducers, and selectors in Redux, simplifying state updates.
  2. Dynamic Updates: Modifications to reactive variables trigger real-time updates in related queries and React components without additional configuration.
  3. Simplicity: Apollo Client's makeVar and useReactiveVar streamline state management, reducing the complexity compared to Redux's actions, reducers, selectors, and middleware.

Benefits of Reactive Variables over React Context

  1. Granular Updates: Reactive variables offer granular control over updates compared to React Context, enabling more specific re-renders only when related variables change using useReactiveVar hook.
  2. Simplicity: React context requires provider components with value and its update function for each state. Which can be more complex to use, especially if you are managing a lot of data.


Code Snippet: Reactive Variables vs. Redux vs. React Context

Redux Example (With Actions, Reducer, and Selectors)

// Redux actions
const ADD_TO_CART = 'ADD_TO_CART';

const addToCart = (item) => ({
  type: ADD_TO_CART,
  payload: item,
});

// Redux reducer
const cartReducer = (state = [], action) => {
  switch (action.type) {
    case ADD_TO_CART:
      return [...state, action.payload];
    default:
      return state;
  }
};

// Redux selectors
const selectCartItems = (state) => state.cart;
const selectCartItemCount = (state) => state.cart.length;

React Context Example (With Provider and Consumer Components)

import React, { createContext, useContext, useState } from 'react';

// Creating context
const CartContext = createContext();

// Providing context at higher level
const CartProvider = ({ children }) => {
  const [cartItems, setCartItems] = useState([]);

  return (
    <CartContext.Provider value={{ cartItems, setCartItems }}>
      {children}
    </CartContext.Provider>
  );
};

// Consuming context in a component
const Cart = () => {
  const { cartItems, setCartItems } = useContext(CartContext);
  // ... rendering logic
};

Apollo Client Reactive Variable

import { makeVar, useReactiveVar } from '@apollo/client';
import { CartItem } from '@types';

// Creating a reactive variable
const initialValue=[]
export const cartItemsVar = makeVar<CartItem[]>([]);

// Using the reactive variable in any component
const Cart = () => {
  const cartItems = useReactiveVar(cartItemsVar);

  const addToCart = (newItem) => {
  // Modifying the reactive variable
    cartItemsVar([...cartItems, newItem]);
  };

  // rendering logic
  return (
    <div>
      <h2>Cart Items</h2>
      <ul>
        {cartItems.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};


Explanation

In the Redux example, actions are defined to perform specific tasks like adding items to the cart. A reducer handles these actions to update the state. Additionally, selectors are created to extract specific portions of the state for use in components.

Contrastingly, with Apollo Client's reactive variables, there is no need to define separate actions, reducers, or selectors. The makeVar function initialises the reactive variable, which can be directly modified with simple functions like cartItemsVar([...cartItems, newItem]).

The use of reactive variables simplifies state management by eliminating the need for multiple files and functions typically required in Redux. This reduction in boilerplate code enhances code readability and maintenance.


Managing Multiple Reactive Variables

In larger applications, managing multiple reactive variables efficiently becomes crucial. Organizing them within a structured folder can enhance maintainability and accessibility across the codebase. Consider the following approach:

Folder Structure Create a dedicated folder, perhaps named reactiveVars, to house all your reactive variables based on different features of the app:

src/
  |- reactiveVars/
      |- cart.ts
      |- user.ts
	  |- settings.ts
      |- ... (other features) 

Each file within the reactiveVars folder can encapsulate a specific feature related reactive variables, ensuring modularity and separation of concerns. For instance, you might have a cart.ts file:

import { makeVar } from '@apollo/client';
import { CartItem, ViewMode } from '@types';

const initialCartItems = [];
export const cartItemsVar = makeVar<CartItem[]>(initialCartItems);
export const isCartOpen = makeVar<boolean>(false);
export const selectedViewMode = makeVar<ViewMode>('grid');

// Other related reactive variables for the cart feature...

This approach helps maintain a coherent structure by grouping related reactive variables within the same feature file. It promotes clarity and ease of access when working on specific functionalities within the application.


Conclusion

Reactive variables in Apollo Client 3 offer a streamlined and efficient alternative to Redux for managing local state. By demonstrating the comparative boilerplate code and complexities between React Context, Redux and Apollo Client's reactive variables, the advantages of using reactive variables become more apparent. And with a feature-based folder structure, we can ensure a more structured and manageable local state management system.

Developers can leverage reactive variables to improve code maintainability and reduce overhead, ultimately simplifying the state management process in their applications.

Subscribe to Our Newsletter

RELATED ARTICLES

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
A real-world look at how oversized images can trigger Safari reloads and iOS crashes in Flutter apps and how smarter image decoding prevents them.
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
This blog explores how Flutter Agent Skills improve AI-assisted development by combining official framework workflows with project-specific guidance for more consistent development.
Why Everything Your AI Builds Looks the Same
Why Everything Your AI Builds Looks the Same
This blog explores why AI-generated interfaces often look alike and explains how design systems, product context, and reusable engineering practices help teams build distinctive, scalable
How We Built the Missing Bridge from Code to Figma
Technology

Jul 10, 2026

How We Built the Missing Bridge from Code to Figma
This blog explores how AI-generated React apps get turned into fully editable, designer-ready Figma files by reading React Fiber instead of the DOM.
Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
Technology

Jun 27, 2026

Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
A practical breakdown of building resilient AWS-to-on-premises connectivity with WireGuard HA, active-standby failover, and deep packet-forwarding observability.
We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
Technology

Jun 19, 2026

We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
A practical guide to building a 114-second multi-cloud disaster recovery failover between AWS and Azure — what we built, what broke, and what we learned.
Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
Technology

Jun 12, 2026

Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
This blog explains how organizations can balance speed, scalability, and operational flexibility as they grow from startup to enterprise scale.

The Right Conversation Can Save You Six Months.

Whether you’re navigating AI adoption, modernizing legacy systems, or scaling a product - we start by listening. No pitch deck. No template. A real conversation.