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!
setState, We Need to Talk!
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
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
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
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
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
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
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.