Boost your React application’s performance by Xstate
Tags: javascript, xstate, performance, react
Published: 2021-02-24 11:08:58

---
title: Boost your React application’s performance by Xstate
published: true
date: 2021-02-24 11:06:09 UTC
tags: javascript,xstate,performance,react
---

![](https://cdn-images-1.medium.com/max/1024/1*taR9Lsd3KRgUK8-hvdCOeA.jpeg)

#### Performance

Is one of the important keys in every application to have better UX and make users happier (of course you may not care about users happiness, but it makes yourself happier 😃 Because you want to do something in a best way and you enjoy it). Performance is different on the web based applications it depends on the tools you choose and how you use them specially on low memory devices like TVs and Mobiles.

#### State Management

There are a lot of libraries out there that you just install and use them in your project. Some people just using the Context Api it self which is powerful and easy to use, but also has some downsides like unnecessary re-renders, Take a look at this example:

{% gist https://gist.github.com/alirezavalizade/ae6eb7fc4c77fd0360d2f6f0f1c978f0 %}

As you can guess, All the nested components get re-render, You are thinking that I’m wrong I can use _useMemo()_ or split the component in two and use _memo()_ , **But everything has a cost so better to avoid them!** [Checkout this interesting article here](https://kentcdodds.com/blog/usememo-and-usecallback) from [Kent C. Dodds](https://medium.com/u/db72389e89d8) If you see the console.count() results in the console then it means React started the [reconciliation](https://reactjs.org/docs/reconciliation.html) process to detect the diffs there in virtual dom. Sometimes this process is not fast enough and you will see the issues and it becomes slow by decreasing frames, sometimes lags in animation like close a Modal. Again checkout this article from [Kent C. Dodds](https://medium.com/u/db72389e89d8) to understand better these downsides in React.

This is just small example and you won’t see the affects but imagine you have thousands of components there. It was really important to me to avoid these kinds of unnecessary re-renders in the application and only update the part that really needs to be update.

Today going to talk about the Xstate and It benefits to share the state between the application.

#### What is Xstate?

[Based on the documents the definition of Xstate is:](https://xstate.js.org/docs/)

> JavaScript and TypeScript [finite state machines](https://en.wikipedia.org/wiki/Finite-state_machine) and [statecharts](https://www.sciencedirect.com/science/article/pii/0167642387900359/pdf) for the modern web.

And a simple example:

{% gist https://gist.github.com/alirezavalizade/7f405965d07a9caefd06d8e72638fbe0 %}

Let’s say we have a music streaming application that user can add/remove items from the library, So the flow will be:

1. Authentication
2. Getting User Profile Information (also on refreshing page to detect if user is already logged in)
3. Getting User Library Information (Musics, Videos, Podcasts and more…- We need this information everywhere not only in one page)

![](https://cdn-images-1.medium.com/max/1024/1*9glz64rTSDNoBJDoiSD3hQ.png)

This sounds really easy and straght forward without Xstate, Isn’t?

It’s possible but it’s not good and clean enough, So the answer is a  **NO** :

1. You need to define the states yourself
2. You need to define the loadings states yourself
3. Your logic and your components getting mixed together, A lots of useEffect(), useState(), useCallback, Promise().then().catch() and callbacks
4. You need to create guards in all the actions, For example you need to check if the latest library is loaded then you can add or remove to/from library
5. A lots of setState since the datas need to be store somewhere and need to be reactive, **This means a lots of re-renders**
6. Hard to debugging since you don’t know the states
7. Hard to have control on the flow

I’m sure there are more.

Behind the state management Xstate gives you powerful control on the flow and different states. If you’re not familiar with the [Xstate first take a look at the documents](https://xstate.js.org/docs/) since this post is not about learning Xstate it’s about using it.

{% gist https://gist.github.com/alirezavalizade/469ab80882c92ca203863e9032278ac0 %}

[See the result in visiualizer](https://xstate.js.org/viz/):

![](https://cdn-images-1.medium.com/max/1023/1*cg1rF1gww2DFBYUzf65dxg.png)

**THIS IS REALLY COOL!** You can define all the steps in the machine and transition between them using events or states itself by target key.

#### Using the machine

In a normal way there are some helpers from @xstate/react package, like useMachine() :

{% gist https://gist.github.com/alirezavalizade/d90d02e01b5c1f062992b61ef3ff05ec %}

All is good, We have 3 different components:

1. LibraryHandler: It doesn’t needs to be update at all since it’s only injected actions.
2. LibraryPresent: It only needs to be update when the library.mp3s item has been updated in the store.
3. UserProfile: It only needs to be update when user item has been updated in the store.

**But** we didn’t solve the issue yet, We still will get those nasty unnecessary re-renders and we wan’t to avoid using memoize helpers. So we need atomic updates, We need to run the machine without passing the state to provider, Here is the place that interpret and useService hook will shine:

{% gist https://gist.github.com/alirezavalizade/44fcfd05763fd1f250e1e48f1c846e1c %}

The authService function will return the service, Eeach service has some useful methods but what we need here are:

1. start(): to start a service
2. stop(): to stop a service
3. send(): to send events
4. subscribe(): to listen to changes

We need to update our AppProvider component and provide the service instead of state directly.

{% gist https://gist.github.com/alirezavalizade/ae1acb4570899bb8caa837b19da5603a %}

So far so good! You see selectors object above that I’ll explain it in a bit.

Let’s create the subscriber hook:

{% gist https://gist.github.com/alirezavalizade/26ab69116f8714ae67f5f8d28be44acd %}

This hooks takes two main arguments:

1. **service: A service that has been started**
2. **selector: A function that receive the state and returns a specific data**

What’s going here?

It’s easy instead of having one global subscriber we have multiple subscribers, And when the component unmounted we unsubscribe the service. This is kind same as redux selectors working.

Let’s update the components that needs the data.

{% gist https://gist.github.com/alirezavalizade/b8ab5a431e18075c44ac1df1b5836afb %}

Yes this is exactly what we need to get out of the re-render hell in React apps with xstate.

#### Summing up

xstate is definitely one of the coolest thing that I have ever worked with it in our applications. It’s helpful for managing the complicate states there are a lot of cooler things that you can do with it. shout out to [David Khourshid](https://medium.com/u/3b9ee2f9eaa2) for creating it.

Thanks for reading, If there is anything I have missed or if there is a better way to do something, Then please let me know. I’d be happy 🤓

You can find me on [Github](https://github.com/alirezavalizade) and [Twitter](https://twitter.com/alirezavlizade)!