DEV Community

Cover image for GraphQL - React X Zustand
Shubham Tiwari
Shubham Tiwari

Posted on

GraphQL - React X Zustand

Hello Everyone, this is the 4th part of our GraphQL Series. In this part, we will discuss how we can consume API created with GraphQL in React JS using the Apollo Client package.

What is Zustand?

Zustand is just a small and efficient state management library just like redux but smaller in size than redux used to create a global state for our Apps.

What is Apollo Client?

With Apollo Client, you can easily connect your React components to a GraphQL API, fetch and manage data, and keep your application's local state synchronized with the server. It offers a declarative and intuitive way to manage your application's data and seamlessly integrate GraphQL into your React components.

How to setup Zustand and Apollo Client in React?

Go to the Main page of your React App and Paste this code

"use client";

import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";
import {create} from 'zustand';

type FormStore = {
  id: number;
  setId: (newId: number) => void;
  name: string;
  setName: (newName: string) => void;
  age: number;
  setAge: (newAge: number) => void;
  role: string;
  setRole: (newRole: string) => void;
  isEmployee: boolean;
  setIsEmployee: (newIsEmployee: boolean) => void;
  isUpdate: boolean;
  setIsUpdate: (newIsUpdate: boolean) => void;

export const useCounterStore = create<FormStore>((set) => ({
    setId:(newId:number) => set({ id: newId }),
    setName:(newName:string) => set({ name: newName }),
    setAge:(newAge:number) => set({ age: newAge }),
    setIsEmployee:(newIsEmployee:boolean) => set({ isEmployee: newIsEmployee }),
    setRole:(newRole:string) => set({ role: newRole }),
    setIsUpdate:(newIsUpdate:boolean) => set({ isUpdate: newIsUpdate })

export default function UsersList() {

  const client = new ApolloClient({
    cache: new InMemoryCache(),
    uri: "http://localhost:4000/graphql",

  return (
    <ApolloProvider client={client}>
Enter fullscreen mode Exit fullscreen mode
  • First we have imported the required packages
  • Then we have defined the Type for our fields to use in our global store in Zustand.
  • Then we have to create the Zustand store and passed the initial values for states and setter functions for those states. We also exported this store to use in other components
  • Then we created a new instance of Apollo Client by passing 2 params URL of our graphql api and cache to set the cache value for our data. We then passed this client instance to the Apollo Provider client prop.

So we have setup our global state and Apollo Client to use in our React App, In next part , we will discuss how we can fetch data and display it in our React App.

You can contact me on -
Instagram -
LinkedIn -
Email -

^^You can help me with some donation at the link below Thank you👇👇 ^^
☕ --> <--

Also check these posts as well

Top comments (0)