Exploring Zustand & Jotai: Efficient State Management Solutions for React App

Exploring Zustand & Jotai: Efficient State Management Solutions for React App

·

5 min read

Managing state in a React app can be a challenging task, especially in video conferencing web apps like Huddle01, due to the complexity of the state involved. In addition to the challenges mentioned earlier, video conferencing web apps also have to deal with:

  • Real-time updates: Video conferencing web apps require real-time updates to multiple streams of data, which can be difficult to manage without causing performance issues.

  • Variable network conditions: Network conditions can vary widely between participants, which can result in different experiences for each participant. Managing this state can be difficult, especially when participants join or leave the call.

  • Participant management: Video conferencing web apps often require complex state management for participant data, including user roles, permissions, and settings. This state can be difficult to manage, especially when participants have different roles or permissions.

Overall, managing state in video conferencing web apps requires a robust and scalable state management solution. Zustand and Jotai are both great choices for managing state in video conferencing web apps, as they provide the flexibility and performance needed to handle complex state structures. However, it's important to carefully consider the requirements of your app and choose a solution that best fits your needs.

What's a state?

State is an essential part of any React application. It represents the current state of the application and determines what the user can see and interact with. Some of the challenges with state management in React include:

  • Prop Drilling: As components become more nested, it can become difficult to pass the state down through multiple levels of the component tree. This can result in a lot of "prop drilling", where the state is passed down through multiple layers of components.

  • Global State: Some state needs to be accessible across the entire application, not just within a single component. Managing the global state can be a challenge, especially when it needs to be updated from multiple components.

  • Performance: As the state changes, React needs to re-render components to reflect those changes. This can be a performance bottleneck, especially when dealing with complex state structures.

Zustand

Zustand is a small, fast, and flexible state management library for React. It provides a simple API for defining and accessing state and can be used in both functional and class components. Zustand uses a store concept to manage the state, and its stores are created using a factory function that returns an object with state and methods to update that state. Zustand also provides middleware support, allowing for easy integration with other libraries like Redux DevTools.

Sneak Peak of what the Huddle01 Zustand State looks like :

One of the key benefits of Zustand is its performance. It uses Immer under the hood, which allows for immutable updates to the state without the need for creating new objects. This means that updates to the state can be made without causing unnecessary re-renders. Zustand also supports asynchronous actions, making it a great choice for applications that require data fetching.

Here's an example of how we’re using Zustand slices to manage state for the sidebar in the Huddle01 App:

Code Snippet:

import type { StateCreator } from 'zustand';
import type { IState } from '../types';
import type { ISidebarStoreState } from '../types/sidebar.client.store.types';
import { SidebarViewEnum } from '../types/sidebar.client.store.types';

const createSidebarSlice: StateCreator<IState, [], [], ISidebarStoreState> = (
  set,
  get
) => ({
  sidebar: {
    isSidebarOpen: false,
    sidebarView: SidebarViewEnum.CLOSE,
  },

  setSidebarView: sidebarView => {
    const prevView = get().sidebar.sidebarView;

    if (sidebarView === 'close' || sidebarView === prevView) {
      set({
        sidebar: {
          isSidebarOpen: false,
          sidebarView: 'close',
        },
      });
      return;
    }

    set({
      sidebar: {
        isSidebarOpen: true,
        sidebarView,
      },
    });

    return;
  },
});

export default createSidebarSlice;

Result

In this example, we define a Zustand store that manages the state related to the sidebar. The store has a state for isSidebarOpen boolean and sidebarView enum which has multiple states (like : chats | peer | tools).

By using Zustand, we can easily define and manage this state in a single place, and the use of Immer under the hood ensures that updates to the state are handled correctly.

Jotai

Jotai is another state management solution for React that uses a different approach to state management. Jotai is based on the concept of atoms, which are units of state that can be composed to create more complex state structures. Atoms are created using a createAtom function that takes an initial value and a function to update that value.

One of the advantages of Jotai is its simplicity. The API is small and easy to learn, and the use of atoms makes it easy to compose and reuse the state. Jotai also supports asynchronous updates to state, and its small size makes it a good choice for applications where performance is important.

Here's an example of how we’re using atomWithStorage from Jotai to handle persistent state for Display Names in the Huddle01 app:

Custom hooks using Jotai to access/modify persistent state:

import { useAtom, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';

const userCachedDisplayNameAtom = atomWithStorage('userDisplayName', '');

export const useUserCachedDisplayName = () =>
  useAtom(userCachedDisplayNameAtom);

Using in UI component:

const [displayName, setDisplayName] = useUserCachedDisplayName();

Result:

The Display Name Jotai state is persisted across all tabs as well as sessions even if we reload

Zustand vs. Jotai

Both Zustand and Jotai provide solutions for managing state in React applications, but they have different approaches to state management.

Zustand uses stores to manage state, while Jotai uses atoms. Zustand provides support for middleware, while Jotai is focused on simplicity and small size.

Conclusion

In this blog post, we discussed two popular state management solutions for React: Zustand and Jotai, while this blog gives a hint of what all is possible with these state management libraries and how Huddle01 is leveraging these state management solutions, there is a lot more to be explored!

Checkout the docs for both these solutions to dive deeper into advanced concepts:

🧸 Zustand

👻 Jotai, primitive and flexible state management for React


The Communication Toolkit for web3, Huddle01 powers decentralised a/v calls & chat for wallets, dApps, DAOs, Communities & users 💬 📞

To keep up with all the updates at Huddle01, follow us on Twitter or join our Discord.