React Context API vs Zustand State Manager

smilepk

Smilepk

Posted on February 19, 2022

React Context API vs Zustand State Manager

This article will show a practical performance comparison between the usage of React Context API and the Zustand State Manager library by solving one scenario with the above-mentioned approaches.
In the production level frontend application that uses React JS, we may need to manage the state. Indeed that is why we focus on frontend frameworks or libraries most of the time. When it comes to the manage our application state globally, we meet lots of state managers or state management patterns and utilities. As we know React JS is quite statable in the market and because of that we can get multiple approaches to manage our frontend application’s state. In this article, I am going to compare the React Context API and the Zustand State Manager with a practical example.
First of all, let's understand what we are going to build.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9gp69pmk8bopcio77kxw.png)
Enter fullscreen mode Exit fullscreen mode

This application contains two main components that show the final winner called the winner component. It will compare the scores achieved by Player A and Player B then show the real-time results. Individual Player' component has their own behavior. By pressing those plus and minus icon buttons scores of each team will be increased or decreased respectively.
I am going to create a Next.js Application for this demo. with that, I will create two routes one for the solution with Context API and the other with the Zustand.


npx create-next-app@latest
# or
yarn create next-app

Enter fullscreen mode Exit fullscreen mode

yarn create next-app
Create a new Next.js Application using the above command and give it a proper name in the installation process. after completing the installation get your app up and running. Then under the pages directory, I created two files called “context-page” and “zustand-page”

Image description

Let's take our first approach using Context API.
This is how we keep the Player scores in the store.


{
     teamA, // Team A's score
     teamB, // Team B's score
     increaseTeamAScore, // Increase Team A's score by one
     decreaseTeamAScore, // Decrease Team A's score by one
     increaseTeamBScore, // Increase Team B's score by one
     decreaseTeamBScore, // Decrease Team B's score by one
}
Enter fullscreen mode Exit fullscreen mode

By keeping in mind of above store design, let’s create our context.

Now we are going to create context-page.js file. This will include the components that we talk earlier with a diagram.

Easy Peasy..!! We Created our first solution with Context API. Go to the route below and check the functionality. Since we are
http://localhost:3000/context-page

Okay, now you can see our solution's appearance is fine and working as we expected. Let’s have a look at this solution from a performance perspective. To do that first of all I am going to term on the “Highlight updates when components render.” feature that comes with React Dev Tools Profiler. I’ll go to the Profiler tab and then click on the Gear icon placed on the top right side. Then I will check the option.

Once that option is enabled, you can see that highlighted sections. It is happening because when we wrap the component tree with Context, it will always rerender all components under the Context Prover when the context change happens.
When we increase or decrease the score of Team A, actually we do not need to rerender the Team B components. since the entire components are wrapped with the StoreContextProvider and actions have done to the Team A component will affect to context, the Team B component also going to reprint. That is why the Team B component also going to be highlighted by the Profiler.
Because scores are compared inside the Winner component, it should rerender. But we do not need to rerender the Team B component. That is the issue with the Context API. It is going to rerender the entire scope that is wrapped with the context provider. But in the real world, we are expecting to rerender changed components only.
To overcome such scenarios, We can take different actions. We can use state managers such as Zustand or libraries like “use-context-selector”. In today's post, I am going to use the Zustand state manager library to overcome this issue.
The store design is the same as above and let's have a deep dive in the Zustand library.
Create a Zustand store.

You can see it is easy to create our store with Zustand and create all action methods to deal with the state. Now we will see how to subscribe a component to the store.

You can see how easily we can subscribe to the store that we created. That is the power of Zustand. It is a small, fast, and scalable barebones state-management solution using simplified flux principles according to their documentation and now we know because we started to use that too.
With the above introduction to Zustand, Let’s create our solution with the help of Zustand. First of all, install the package to our Application.
yarn add zustan # or dnpm install zustand
Then let’s create the “zustand-page.js” file with the solution.

Okay, we have addressed the same problem but with a different solution. We can see the expected behavior achieved and now let’s see how the rerendering happens.

According to the Profiler, now you can see how the rerenders happen. With the help of Zustand, we have achieved the perfoamce issue too. And the creation of the store and subscribing to the Components are also pretty straightforward.
There are a lot more features offered with the Zustand. You can go through their documentation and find more.
Thank you for reading 🙏.
It would help me a lot 😁
React
React Context Api
Prop Drilling

Context Api
3

1

More from Vimukthi Jayasinghe
Follow

Experienced Software Engineer with a demonstrated history of working in the computer software industry.
More From Medium
Angular Performance: Web Workers
Chidume Nnamdi 🔥💻🎵🎮 in Bits and Pieces

How to implement JestJS on existing website
Andy Greco

Greedy algorithms
chathurya

Intigriti’s December XSS challenge By E1u5iv3F0x
Martin Stoynov

Chapter 11: How to build a Google Home App with DialogFlow | Fulfillment via Webhook
Moses Sam Paul in Heptagon

React Native — Full authentication flow with Spotify— Chapter 2: Backend Proxy (Firebase Functions…
Thomas Swolfs

Asynchronous communication in JavaScript: fetch() vs ajax()
William Harris

How to Debug a TypeScript Node.js App in Visual Studio Code
Bilal Rifas in JavaScript in Plain English

About
Write
Help
Legal
Get the Medium app
A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

💖 💪 🙅 🚩
smilepk
Smilepk

Posted on February 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related