setState, We Need to Talk!

Rate this content

One of the biggest pain points when developing an app is the tricky business of managing state, race conditions, etc. Finite state machines can help eliminate such bugs entirely while providing a welcome, structured way to build components. Looks cool? Let’s build one, it’s even cooler!

20 min
25 Oct, 2021

AI Generated Video Summary

In this Talk, the speaker discusses the importance of planning and maintaining UIs in React using state machines. They highlight the need to consider user experience and plan for performance and maintainability. The challenges of handling multiple UI states are addressed, and the benefits of using finite state machines are explained. The speaker demonstrates how to implement transitions and update the UI using a React state machine. They emphasize the benefits of state machines in handling errors, avoiding state explosions, and improving collaboration between designers and developers.

1. Introduction to UI Planning and Maintenance

Short description:

In this session, I would like to discuss how we think UIs in React and how state machines can help us build more performance and easy to maintain UIs. As time has progressed, developers and designers have started to think more about user experience and the solutions to complex problems. With rich UIs, users can surprise us by using our apps in ways we may not have imagined, highlighting the need to plan UIs better. We often focus on implementation rather than maintenance, but it's crucial to plan for performance and maintainability.

Hey, everyone. So thank you all for joining us at React Advanced London. Hope you all are having a great time enjoying such enlightening and insightful talks. So in this session, I would like to discuss how do we think UIs in React and how like state machines can help us like build more performance and like more easy to maintain and bug-free ones in the future.

So before diving in, a little bit about me. So for the ones who don't know me, hey, I'm Nikhil. I'm a software engineer at Postman. I mostly handle stuff around Postman on the web and Postman's desktop platform. I love to also talk about design systems and performance in general. So here are my Twitter and GitHub links. I'll be glad to connect and have a chat.

So moving forward, let's start with the thought that while building more complex problems, we have started to develop more complex solutions with time to make the lives of users easier, right? So it's a known fact that right now, back at the old times, we did not have those amount of complex problems to solve. And neither did we have the right tools and the right set of things to make our UIs more richer and more performant like we have right now. And that's basically the reason why we mostly had some static websites and stuff like that, where we did not need any of the inputs from users. We did not expect users to interact much with our websites rather than what we have right now is more of web apps where there is a ton of user interaction, right?

So as the time has progressed, developers and designers had started to think more upon things around user experience and sorted the solutions. And as things have become more complex and as we are trying to solve more complex problems, the solutions or the UI we are now building start to become more and more dense and more complex because now they have a ton of more things to offer to the user, right? So with such a rich UI, the users always get a chance to surprise us, developers, by using our apps in a ton of different ways where we might not have imagined them using it this way or we might not have accounted that particular way for. So a user might use your app in a whole different ways which you might have not thought of and that actually highlights the need of us now planning our UIs better. So now is the real need for us that we need to plan our UIs. And I would rather say that it's like not only up to the users, it's also us that we mostly follow the plan of implementation rather than the plan of maintenance, right? So we are mostly into this concept of that, hey, I have a UI to build, let me just go and define what are things where I need to have, what are my effects that I need to run, what are the logic that I need to run on an onChange and on input and stuff like that. It's like we are more into nitty-gritties of implementation rather than taking a step back and thinking more upon how we can start with maintenance and how we can start planning our UIs better so that they are more performant and more maintainable in the future.

2. UIs and Handling Messages

Short description:

Let's consider a basic login form with two text inputs for username and password, and a button to log in. However, we need to think about handling success or error messages in the future.

All right, with that being said, let's try to see things in action by considering a very simple example. So, as you see, there has the small code snippet of a basic login form. And what this does is like you have two text inputs, a user ID, a password, and then there's a button at the end where you click on it and it either logs you in or it just shows you in an edit. If you would ask me that how we are right now thinking in UIs, what we would start diving upon is, okay, there are two states. We have username and password, done and done. Then we think of, okay, there is an async part that we have to do. So, let's create a function on top of that to do that async stuff, which in this case is to click on a button and send that data so that we are able to log in. And thirdly, we just think of, okay, there is some UI that needs to be rendered. So, okay, let me just render two text boxes, one button, and we are done. And you might be thinking that, hey, man, why would we need this topic in the first place? This is so much obvious to do, right? And that is where I would say that, hey, this is a very minimal thing, right? What if I want to show a sort of a success or an error message in the future? So, right now, we just have a text input, a username, password, and then a button. And I just click on it, and that's it. So, what if I have to show such type of messages to the user?

3. Challenges of Handling Multiple UI States

Short description:

And now we see that handling multiple states in our UI can become difficult to maintain, lead to state explosion, and make code visualization challenging. As our UIs become more complex, it's crucial to plan ahead for better code maintainability, bug detection, and code visualization.

And now we see that, okay, two more states. Not an issue. And then inside our asynchronous task, we handle how we toggle these states. So, as you see in the summit form function, if everything works out well for our async data, we set this is success to true. And if not, we then set is error to true. And inside our UI spot, we then do, okay, if there's a success, okay, we have logged in successfully. And else we just show a paragraph that, okay, there's some error.

All right, let's try to think more deeper in terms of, okay, what if I want to disable a button? And then you would say that, all right, another stage, some more work to do on summit form. And then I have to disable this button on this loading state based on this loading Boolean flag. And now that's this, and now I think you are able to realize what I'm gonna go to, right? So, first of all, the problems with this type of an approach is, firstly, this is difficult to maintain. These are just few states right now, but as this form starts to become more complex and like more mature, there are gonna be a ton of more states and it's gonna be really difficult to handle them in the future since this length of code starts to increase so much. Secondly, there is a concept called state explosion, right? So right now I just have mainly three states to have my UI ready, but if you see on a broader picture, we have two to the power three, that's eight permutations and combinations in which our states can exist. There are basically eight ways where a UI might exist if you see mathematically. Honestly, you might not basically need those states anywhere in the future or like those might not have to be handled, but, hey, the user can access it or like reach to that state in like any other form. So you have to account on that. And thirdly, and thirdly, and most importantly, this is really difficult to visualize, right? Because your app has a soul, which is that logic of your app where you are doing that logical thinking part of your app. And with that logic being spread, like sugar spread around different parts of your app, it's really difficult to make sense out of this code if I'm a new developer and I start to work on this code. So it's very difficult to understand. And basically that's what I call a Horcrux code. So if there are Harry Potter fans in the audience, I think you all know that. So like this Horcrux, so like this is a Horcrux where you had select these, which is had a way of creating, it's like they could just keep the part of their soul inside one place and a part of that soul in another. So that is what's happening inside our code base. So the soul of our app or soul of our code, that is our logic is being spread across multiple places. And like this is why it's very difficult to visualize that code. And this is a very small example, as you all might have seen, we have a lot more complexity in our UIs and a lot more features to offer. And it's just like not just more about a login form, but it's much more than that as our UIs have started to become tremendously complex and big. So now we know that, right? That planning is really important. And with planning you can like make your code maintainable. You can catch bugs easily. You can make your code more visualizable and that helps you.

4. Introduction to Finite State Machines

Short description:

You can make your code more visualizable by planning UIs using finite state machines. Finite state machines offer a better way to plan UIs, focusing on maintainability rather than just implementation. They provide an initial state and allow transitions between states based on actions. By defining the possible states and transitions, UI behavior becomes more predictable. This logic is centralized in a transition function, which determines the next state based on the current state and action. Implementing this approach can make your UI more manageable and easier to understand.

You can make your code more visualizable and that helps you. But what are we doing with planning, right? We are mostly following the concept of implementation sourced planning, right? And not maintainability source planning. So with that example previously that we showed, we are mostly thinking about, okay, what is there on our effects? What are the props? What are the states and whatnot? And that actually brings us to a conclusion that what can be a better way, right? What can be a better way of planning our UIs rather than planning implementation.

And now you might be able to see that since we have a lot of states and there can be a lot of permutations and combinations of those states in the future, there has to be a way, or there has to be some sort of a system where we can be saved from this multiple if else statements to handle what to do when this state is there and this state is not there. There might be a system where we can just check and we can just orchestrate our states and transitions between those states in a better way. And obviously you guessed it, right. So there comes finite state machines to our rescue.

So if I had to put this in a very simpler way what finite state machines have to offer is basically you have an initial state or initial condition or an initial situation of the UI, which it might be in. And then you might perform some action with that state. And like if that state receives an action, it goes on to a next state. And at every point of time, each state knows based on an action that what is gonna be the next state that UI or your code is gonna go through. And that's what these three words mean, right? You have a finite number of states. You have a state obviously, which is a condition or the situation your UI is in. And basically there's a machine, which is orchestrating that state and how those states transition based on actions. So that is mostly the whole point of a finite state machine. All right, so that being said, let's try to start thinking about how we can think in state machines with that.

All right, so with that example in mind, we are mostly going to see that, okay, there are basically four types with which a UI can exist. Either it can be idle or I might click the button to make my UI go in a loading state that, okay, I'm being logged in. And if I logged in successfully, I go to an isSuccess state or I go to an isError state. And that's what makes our transitions defined. We define that, okay, what is the current state and based on that what are the transitions that that state can go to and like what's that next state. And basically that being said, you have a state, you have an action. For example, if I'm in an idle state, I do an action called submitForm and then I go to a state called isLoading. And that's how you visualize things and how you create a mental model of state machines in your mind.

So, if you see a mapping between your visual and code, it's just basically on the right side that you see two simple objects where a state subject just defines what are these circles on the left, which are the states that you have. And this transitions object just lets you know that, okay, if I am on a state, let's say, states.idle, and I perform an action called submitForm, I go to a state called states.loading. So that makes your UI more predictable and like there's this logic all at one place. And obviously, since we have this brain ready, we have to tell this brain how to communicate between its other states, right? So, this is a function called transition. And what it does is like, basically, it knows that, okay, what's the current state? What's the action? And based on this, where do I have to go to the next state? And this brain and the body being set up this machine, you just have a simple function just down below, which is updateForm state, where you just do nothing but just let transition tell you that, okay, what's the next state? And I just set my state based on that.

All right, so, enough being said, I think you're bored of all this theories.

5. Implementing Transitions and Updating the UI

Short description:

Let's implement the transitions in our form and update the UI accordingly. If the form submission is successful, we update the form state. Otherwise, if there is an error, we display the error message. By centralizing our logic in a React state machine, we have a single place to manage all the form behavior. This approach simplifies debugging and improves the overall maintainability of our app.

So, let's try to go inside, what is the real action? All right, so, this is the simple example of this form. And now this has been just implemented with that implementation detail approach that we had in mind, right? So, let me bring in that boilerplate code, right? I already have this written here. So, let me just take this, I copy this inside my function. Let's have it right here. All right, let me just uncomment this. Okay, so, we are ready. And I don't need these all states right now because I have this machine in place.

Okay, so now, let's do some actions with our transitions. Okay, so, when we are loading this, we can instead do, okay, update form state. All right, and we do submit form. So, now we go to a transition from one state to another. If everything is a success, we update the form state. All right, so, form, or, I think submit form, success, so, like, we perform this action to go to the next state. Or else, if nothing turns out good and I cannot be logged in, I just do submit, or, submit, form, error. All right, and based on this, while we have these transitions in place, let's update how we are rendering the UI. Okay, so, how this success comes is if the current state is equals, is success, and if the current state that we have been tracking is stage.isError. That means, if we got the error and our state machine is in that error state, we just show that same message. And talking about a button to be disabled, I'll just say, okay, current state is state.isError. And that's mostly it, and that's most of the factors that you need, right. Let's just quickly refresh, and yeah. Let's quickly see if that turns out well. So, maybe I enter a username, or I enter a password. I try to log in. And yes, that works. Yeah, the error is contrived, but this part works. And that's the beauty of a React state machine, right, because all of your logic is now at just a single place. And there is, this is that only place that you want to go to when you are reading this code, right? And how awesome is that? All right. With that in mind, let's try to see what are the achievements that we got. So, obviously no hope access, because now you have unified the soul of your app into just one piece and not distributed. Obviously, it's easy to debug, because now you have a visualization in mind, and you can just now see that, okay, if my form is not behaving well, there is something that I have done wrong or like something that I've not created inside my state machine.

6. Benefits of State Machines and Closing Remarks

Short description:

State machines can help in handling errors, avoiding state explosions, and managing race conditions. They also facilitate collaboration between designers and developers. It's important to use state machines only when necessary and when the UI logic needs to be visualized. Consider using the XState library for state machine implementation. Lastly, thank you to React Advanced London and the audience for making this presentation a success.

So you know, like where to look for as an error, like, or where to look for other than this whole code. And obviously, no state explosions, because rather than three, you now have just a single state, and that has been orchestrated all via state machine.

Now, another thing that we already had as an issue were race conditions, where you are trying to do some asynchronous tasks, and there are a number of them lined up, and you don't know what the order can be. And that is a beauty of state machines and how they can help you, right? That at one point of time, your UI can just only be in one state and not in many parallel states. So if you have defined your state machines well, you won't be having an issue with the race conditions. So that is being handled gracefully.

Another very important thing that I have felt is a designer to developer collaboration, because I feel that mostly all of the designers have a mental model of thinking in state machines. So the next time, if you are going to be collaborating with the designers, you would know what to look for or what to ask them and what is those number of conditions or situations of a UI where you would need an input from a designer. So you know the state machines, you know the most possible ways where your UI can behave. And that is how a designer is actually working. So like that makes the process more streamlined.

And you also might be thinking that, hey, now I have this power of state machines, so let me just go in my code base and change everything with state machines. And I would not recommend that. So I would rather say that if there is a need for a state machine that could mostly arise if your code or if your component is very complex and there's a need of being visualized in terms of its logic. And that has been very well said by David Kushnick in one of his tweets and I really believe in what he mentioned that if the UI is visualized and that UI has a soul or a logic inside it that has to be visualized, then definitely we must work with the state machines because our main motive is to make our code readable and maintainable and not to apply state machines on top of that. So, yeah, I would say just keep that part in mind to avoid big days trying to just update things to state machines.

So just to mention as a side note here are gonna be the useful links that you might need. Here's a link to the course handbook that I had been showing you in the demo and also the link to the slides. So you can catch all those here.

Last but not the least, I would like to mention is try this library called XState if you would like to dive in into this magic of state machines. This is a great library I've tried it and I personally recommend it to all the folks who would like want to add state machines to their project. So it just helps you add minimalistic code and avoid all of those mambo jumbos and boiler plates that we added in our demo. So try this out, I think you would really love this. So kudos to David for this.

So on a side note, again, we are hiring at Postman. So it would be like to be part of a journey of building the product. Come say hi and you can connect to us via our careers website.

So that's all that I had for this presentation. So a big thanks to the React Advanced London, the people who had been involved in organizing this and making it a big success. So hats up to you guys. And last but not the least, you guys the audience, thank you for having me. I love having this chat and discussing things around. So see you guys next time, signing off.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Remix is a new web framework from the creators of React Router that helps you build better, faster websites through a solid understanding of web fundamentals. Remix takes care of the heavy lifting like server rendering, code splitting, prefetching, and navigation and leaves you with the fun part: building something awesome!
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
When we think about Vuex, Pinia, or stores in general we often think about state management and the Flux patterns but not only do stores not always follow the Flux pattern, there is so much more about stores that make them worth using! Plugins, Devtools, server-side rendering, TypeScript integrations... Let's dive into everything beyond state management with Pinia with practical examples about plugins and Devtools to get the most out of your stores.
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Featured WorkshopFree
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Featured Workshop
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Featured WorkshopFree
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Featured WorkshopFree
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Featured Workshop
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn