Multi-Style Tailwind Components 23 exercises

Modal State Management Patterns

To wrap up this section, let's discuss state management patterns in relation to the modal component.

In our current implementation, we have two boolean props open and isLoading.


Loading explainer


0:00 To wrap up this segment, I want to make a quick observation on state management patterns. In our ModalProps, I see two specific boolean props that share some common surface area. That typically should make you stop and think.

0:11 Open and isLoading here are managed independently. We literally have an isOpen piece of state and an isLoading piece of state. They both work together in determining whether the modal should be open, closed, or frozen while loading.

0:26 There isn't honestly much complexity in our modal, yet we've already faced some scenarios where we have a broken state. The modal is closed but loading. That shouldn't happen.

0:35 Also, with complexity creeping in, we may need more states than just isLoading. What about error, success, installing? What I'm saying is working with booleans is somewhat limiting, and working with multiple booleans working together can lead to really weird states.

0:49 A much nicer approach here would be to have one single property, an enum, that lists all the possible states that our modal can be in. The modal should only be able to be in one of these states at any time. Essentially, this would lead to a list of finite, predictable lists of possible states.

1:06 What that would look like in our code, instead of having open and isLoading, would be something like a status prop, where our modal could be open or closed, and also maybe loading. This single prop could already play the role of both the open and isLoading.

1:23 Status open would be open true, isLoading . Status closed would be open , isLoading , and status loading would be open true, isLoading true. By doing this, we remove the risk of having the modal closed but loading, like we had to cater for before.

1:40 As new scenarios happen, maybe it's been loading for seven straight seconds, and you want to have a new state called stalling, where you could display a little notice saying, "Hey, it's taking a bit longer than usual. We're still trying. Please hang in there," or something like that.

1:54 You could also use this to handle error states and so on. You get the idea. That approach to me is more scalable and future-proof, but more importantly, it removes a lot of these weird states and bugs your application can be in when you use multiple booleans combined together.

2:09 This is state management talk, but it also has a real implication on styling. In the next and final chapter of this module, we're going to refactor some codes that I wrote using multiple boolean props to handle styling, and quite frankly, made a mess.