DEV Community

Cover image for React | Context API vs Zustand
Shubham Tiwari
Shubham Tiwari

Posted on

React | Context API vs Zustand

Hello my fellow developers, today we will be discussing about react context api and zustand.

Introduction

  • React's useContext is a built-in hook that allows you to share state across your application without passing props down manually at every level.

  • Zustand is a small, fast, and scalable bearbones state management library that aims to provide a more straightforward way of managing global state in React applications.

Overview of useContext

What is useContext?

useContext is a React hook that allows you to consume context values without the need to wrap components in Context.Consumer.

How to Use useContext

1. Create a context



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

const MyContext = createContext();

const MyProvider = ({ children }) => {
  const [state, setState] = useState('default value');

  return (
    <MyContext.Provider value={{ state, setState }}>
      {children}
    </MyContext.Provider>
  );
};


Enter fullscreen mode Exit fullscreen mode

2. Consume a context



const MyComponent = () => {
  const { state, setState } = useContext(MyContext);

  return (
    <div>
      <p>{state}</p>
      <button onClick={() => setState('new value')}>Change State</button>
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

Use Cases:

  • Sharing state across many components

  • Avoiding prop drilling

Overview of Zustand

What is Zustand?

Zustand is a small, fast, and flexible state management library that uses hooks for managing state in React applications. It is more lightweight and easier to use than some of the more comprehensive state management solutions like Redux.

How to Use Zustand

1. Install Zustand:



npm install zustand


Enter fullscreen mode Exit fullscreen mode

2. Create a store



import create from 'zustand';

const useStore = create((set) => ({
  state: 'default value',
  setState: (newState) => set({ state: newState })
}));


Enter fullscreen mode Exit fullscreen mode

3. Consume the store



const MyComponent = () => {
  const { state, setState } = useStore();

  return (
    <div>
      <p>{state}</p>
      <button onClick={() => setState('new value')}>Change State</button>
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

Use Cases

  • Global state management

  • Small to medium-sized applications

  • Performance-critical applications

Differences Between useContext and Zustand

Context API Zustant
Setup Complexity Simple and straightforward, part of React. Requires an additional library and setup but provides more features.
Performance May cause performance issues with deeply nested components and frequent re-renders. Optimized for performance with minimal re-renders and better scalability.:
State Management Suitable for simpler state sharing. Better for more complex state management needs, with features like middleware, persistence, and actions.
Scalability Less scalable for large applications. More scalable with better separation of concerns.
Persistence useContext does not have built-in support for persisting state across sessions. If you need to persist state (e.g., across page reloads), you typically need to implement this manually using browser storage APIs like localStorage or sessionStorage. This requires additional code to save and retrieve context state from storage, and to initialize context state from storage on app startup. Zustand has built-in support for persisting state. Zustand can easily integrate with browser storage APIs, allowing you to persist and rehydrate state with minimal boilerplate. This is typically achieved by using middleware provided by Zustand, such as zustand/middleware.

Persisting State with Zustand

Install Zustand Middleware:



npm install zustand zustand/middleware


Enter fullscreen mode Exit fullscreen mode

Create a persisted store



import create from 'zustand';
import { persist } from 'zustand/middleware';

const useStore = create(
  persist(
    (set) => ({
      state: 'default value',
      setState: (newState) => set({ state: newState })
    }),
    {
      name: 'my-store', // unique name
      getStorage: () => localStorage // use localStorage or sessionStorage for persistence
    }
  )
);


Enter fullscreen mode Exit fullscreen mode

Consume the store as usual



const MyComponent = () => {
  const { state, setState } = useStore();

  return (
    <div>
      <p>{state}</p>
      <button onClick={() => setState('new value')}>Change State</button>
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

Pros and Cons of useContext

Pros

  • Built-in: No need for external libraries.

  • Simple API: Easy to understand and use.

  • Integrated: Works seamlessly with other React features.

Cons

  • Performance: Can cause unnecessary re-renders.

  • Scalability: Not suitable for large applications.

  • Boilerplate: Requires a lot of boilerplate for complex state.

Pros and Cons of Zustand

Pros

  • Performance: Optimized for minimal re-renders.

  • Scalability: Better for larger applications.

  • Flexibility: More features for complex state management.

  • Simplicity: Simple API and minimal boilerplate.

Cons

  • External Dependency: Requires an additional library.

  • Learning Curve: May have a slight learning curve for new users.

Conclusion

While useContext is a powerful tool for simple state sharing in React, Zustand offers a more efficient and scalable solution for managing global state, especially in larger applications. By replacing useContext with Zustand, you can achieve better performance and maintainability.

THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

You can help me with some donation at the link below Thank you👇👇
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well

Top comments (3)

Collapse
 
axl_rose_86f614dd71d6544a profile image
Axl rose

I believe the two serve different purposes. Zustand is well-suited for global state management, while Context works best for local state, so using both in tandem seems appropriate. For instance, if we were to use Zustand to manage state and execute actions for each item in a list UI, it could become quite complex. However, Context can be used independently within each tree, regardless of its position, and it automatically clears unused data from memory upon unmounting. These two complement each other rather than requiring an exclusive choice of one over the other.

Collapse
 
blenderman profile image
BBM

Thank you for sharing this comparison between Context API and Zustand! Could you go into more detail about the scenarios where Zustand's built-in persistence would be particularly beneficial?

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Yeah I have 1 example for using the persistence, I had worked on a service providing website where I had a register form on the home page, after registration there should be a plans cards section in place of the register form, I used the zustand persistence to check if there is a session storage created by zustand while doing the registration to create condition in UI to show the plans card section if the session is there, else it will show the registration form
It was quite useful as it works as expected even if we refresh the page
Also while logging out, just clear the session created by zustand and it will show the registration form again