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.

Search for a command to run...
Explore the power of Apollo Client 3's Reactive Variables for seamless local state management.

No comments yet. Be the first to comment.
Is the local IDE dead? Sanket Sahu discusses the rise of 'vibe-coding' and how browser-native tools like RapidNative are reshaping the future of mobile app development.

OpenClaw is a powerful, self-hosted AI assistant that connects to your tools to perform actions. Explore its Gateway architecture, real-world use cases, and security precautions.

Discover how neo-brutalism is shaping 2026 design trends. See how anti-design principles can create distinct, usable, and memorable product experiences.

When code breaks a pipeline, developers have to stop working and figure out why. This blog shows how an AI agent reads the error, finds the fix, and submits it for review all on its own.

GeekyAnts built a 5-agent fraud detection pipeline that makes decisions in under 200ms — 15x cheaper than single-model systems, with full explainability built in.

GeekyAnts Tech Blog
349 posts
GeekyAnts is an AI-powered digital product engineering and consulting company helping startups, enterprises, and Fortune 500 brands build scalable, future-ready digital solutions. Since 2006, we have delivered 800+ successful projects for 550+ global clients across healthcare, BFSI, retail, logistics, education, and enterprise technology. We help businesses accelerate digital transformation through strategy, design, engineering, and AI-led innovation.
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.
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.
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);
Reading the value:
const cartItems = cartItemsVar();
Modifying the value:
cartItemsVar([...cartItems, newItem]);
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);
// ...
Reduced Boilerplate: Reactive variables eliminate the need for multiple actions, reducers, and selectors in Redux, simplifying state updates.
Dynamic Updates: Modifications to reactive variables trigger real-time updates in related queries and React components without additional configuration.
Simplicity: Apollo Client's makeVar and useReactiveVar streamline state management, reducing the complexity compared to Redux's actions, reducers, selectors, and middleware.
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.
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.
// 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;
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
};
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>
);
};
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.
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.
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.
This article was written by Simranjit Singh, Senior Software Engineer - I, for the GeekyAnts blog.