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!
Transcription
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 state machines can help us build more performant and 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, I'm Nikhil. I'm a software engineer at Postman. I mostly handle stuff around Postman on the web and Postman is just a 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. So it's a known fact that right now, like 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. So as the time has progressed, developers and designers have started to think more upon things around user experience and so did 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. 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 not only up to the users. It's also us that we mostly follow the plan of implementation rather than the plan of maintenance. So we are mostly into this concept of, hey, I have a UI to build. Let me just go and define what are things I need to have, what are my effects that I need to run, what are the logic that I need to run on an on change and stuff like that. We are more into the 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. 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 is this small code snippet of a basic login form. And what this does is 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 an error. If you would ask me how we are right now thinking in UIs, what we would start diving upon is, okay, there are two states. We have user name 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, 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? Right now we have a text input, a user name, 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? All right. Now you might be thinking, okay, now work has started to develop on us. And now we see, 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 success to true. And if not, we then set 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 going to 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 three states right now. But as this form starts to become more complex and more mature, there are going to be a ton of more states and it's going to 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 our UI might exist if you see mathematically. Honestly, you might not basically need those states anywhere in the future or those might not have to be handled. But hey, the user can access it or reach to that state in 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 the logic of your app, where you're 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, so like they could just keep the part of the 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. But what are we doing with planning? Right? We are mostly following the concept of implementation source planning, right? And not maintainability source planning. So with our 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 like 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 a 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 going to be the next state that your UI or your code is going to 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, right? 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 log in successfully, I go to an is success state or I go to an is error state. And that's what makes our transitions defined, right? 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 submit form and then I go to a state called is loading. 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's object just defines what are the circles on the left, which are the states that you have. And this transitions object just lets you know that, okay, if I'm on a state, let's say states.idle, and I perform an action called submit form, I go to a state called state.loading. So that's making your UI more predictable. And 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 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 update form 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 these theories. So let's try to go inside what is the real action. All right. So there's the simple example of this form, right? And now this is being 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 copied 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 that transitions. Okay. So like 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 I just do form or submit form success. 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 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 states.is error. 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 our button to be disabled, I just say, okay, current state is states.is loading. 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 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. All of your logic is at just a single place. And this is the only place that you want to go to when you're reading this code. 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 now you have unified the soul of your app into just one piece and not distributed. Obviously 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 something that I have not catered inside my state machine. So you know where to look for as an error or where to look for other than this whole code. And obviously no state explosions. Because other than three, you now have just a single state. And that is being orchestrated all by a 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 the beauty of state machines and how they can help you. At one point in time, your UI can just only be in one state and not in many parallel states. So if you define your state machines well, you won't be having an issue with 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 your UI can behave, and that is how a designer is actually working. So 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 would 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 is mostly and that has been very well said by David Cushy 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 going to be the useful links that you might need. Here's a link to the code sandbox 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 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. It really adds, it really just helps you add minimalistic code and avoid all of those mambo jambos and boilerplates 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 a part of our journey of building the product. Come say hi and you can connect with 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 off 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.