Welcome to the React Show, brought to you from Occupied Miwok Territory by me, your host, Thomas, and a beautiful sunrise, episode 66. How do you go from idea to creating a solid React application? How do you break your plan down into components? How do you think in React? Thank you for joining us. We have an awesome episode for you all today. It starts with a fun little experiment I ran where we stored React state inside refs instead of hooks or context like normal. I found it kind of mind-blowing in what it enables you to do. And then we get into how to actually create really great React applications in a very natural way where you won't get stuck so easily. I'm, of course, uh really excited because this means we get to talk about both React and Good Design. And if you know me, those are two of my favorite things. Yeah, and if you like learning about React and how to create great React applications, come join us on our Patreon where you can interact directly with us, uh, support the show, and even get a free copy of my book. So, yeah, if you like the podcast, you want to uh support the show, come join us on Patreon. And now that I've finished drinking my coffee and made a few plugs, it's time to get into that experiment I talked about. What actually happens if you store state in a ref? All right, so this experiment is completely around exploring this idea. So, first of all, let me just mention like what is a ref. So if you've done much React development, normally you will store your state inside like the use state hook, or you know, if you're using class-based components, the uh state gets stored, you know, in the class, or maybe you store it in a context or something like that. That's a normal way that we we use state within React, but you may have also run across refs and you may have even used them. Refs are essentially another way to store state in a React component. So the state itself will be associated with an instance of that component. But you can change that state and it won't cause React to re-render whatever component that ref is specified in. So it's different than normal, the normal way of storing state in React, where whenever you change the value of that state, it causes React to re-render that component and update what the user sees on their screen. So, anyways, I was just like, hey, what can we do with this? Is there some other cool use for this beyond what you know people often use it for, which is sort of like connecting your React application to the DOM and stuff like that? And so, yeah, I just wanted to set up an experiment where we can explore what refs do and what they allow us to do. And this is based on a previous experiment I talked about in a previous episode, where we just use regular JavaScript variables to store state. You know, I was curious about what the effects of using refs to store all of our state would be instead of storing it in those regular JavaScript variables. So the experiment is I create a React application, which is essentially an animation with a ball moving across the screen. I created two versions of this experiment for tracking the state of the ball. One was just using traditional React use state hook. So the position of the ball on the screen is stored in a use state, you know, variable, and I update it and read it from that variable. But in the other version of this experiment, I stored the state in a ref. And if you're not familiar with it, you can look up the ref API. Um, you can call use ref, and and it's sort of like essentially like use state. But, anyways, so I stored the the position of the ball in a ref, but then I added a regular use state variable that I could selectively change to trigger React to re-render. So this essentially allowed me to decouple the state of my application from when React re-renders. Essentially, I could update the position of the ball without triggering React to re-render and show that new position. So this might sound kind of weird. Like, why would you ever want to do that? But we'll get into it. I think there are actually interesting reasons. But yeah, so essentially we have two versions. One is just regular React. Uh, it's if you were to go create this yourself, it would be like that, the position of the ball, you know, stored in the X, Y, use state variable. And the other one, it's stored in a ref. All right, so I ran this, um, both versions, and I just sort of wanted to look at the performance and sort of the design characteristics. So when it comes to performance, you might think, okay, if I store my state not in the use state variable, and when I change that state, it doesn't cause React to re-render my code, it's going to be way faster, right? Like React takes time to do its reacting, you know. But what I found was actually interesting. So even if I never told React to re-render, I just kept updating the state inside my ref and my component code itself never re-ran after the initial render. I actually found that the overall CPU and GPU usage between the two versions was essentially the same. There's a very slight decrease in CPU and GPU usage on the ref only version. But I was really surprised that essentially they were the same. And the way I set up the experiment is I basically created it so that it would run this code over and over again as fast as it could, the code that updates where the ball is on the screen, essentially running the animation. So, in overall, you know, resource usage, it looked like it didn't matter much. But then I also captured a browser profile of each version of the experiment. And it did show that the use state version spent six times more time executing script code. So clearly it was doing a lot more work in terms of you know the internals of React itself, but that actually didn't have much overall impact on the end user's resource usage. And we'll maybe dive into this a little bit more at the end, um, why that might be. But I thought this was really interesting, you know, like some people I've heard suggest using refs and setting up something like this can help you improve performance. And maybe it can in certain cases, but I was really surprised to find that sort of by default, it didn't actually have that much effect. But the more interesting thing to me actually was in the code itself. So it wasn't really so much about the performance, but it actually changed the way that you write the code. So the ref-based code allowed me to decouple re-renders from the internal application state updates. It feels cool, but it also has some advantages. So one of the big advantages is I could write the animation algorithm independent of the timer that causes what the user sees to get updated on the screen. So essentially, the code for updating the animation is simpler with a ref because it's decoupled with from the updates on the screen. So essentially, you could be like, I want to run my animation 10,000 times per second, uh, but the user screen maybe only updates once every 16 milliseconds. And so um we're only gonna re-render our React component once every 16 milliseconds. And so I can write two different algorithms, one that controls the current state of the animation, and the second algorithm, which controls when this state gets resynced to what the user sees. Now, if you've done much like game development, you'll probably recognize this pattern. This is how most games are written. They're essentially written to, you know, run all the code for your game engine as fast as it possibly can, but only update the user's display when it really needs to be updated. And so this is really cool, I think, especially for animation type code, because it allows you to write sort of cleaner code and allows you to really easily adjust the smoothness of the animation. So you could, you know, maybe have give up some performance for a smoother animation, or maybe in some cases it's not as important. And you can easily make that trade-off if these two algorithms are separate. But if you use the use state version, those are coupled together. Every time you change the data, it's going to re-render and attempt to update what's on the display. Now, what I will say is I've learned through this experiment that it's actually way more complicated than this. Um, for example, it as far as I can tell, effectively, you know, Firefox and Chrome and Safari, the major browsers, they actually don't let you update faster than like once per millisecond. And in a lot of cases, the fastest they'll do updates is like once every four milliseconds. So depending on how you've set up these algorithms, that might be one reason why we why you might not see a big difference in performance, because the browser might just be ignoring some of the updates that come from React that happen, you know, like if you re-render your React component, like, you know, if you attempt to re-render it like 10 times within a millisecond, what you'll probably find is that that code either doesn't get run that frequently or the browser doesn't update that frequently. So there's a lot of like internal browser characteristics that come into play here. Um, so that's why when it comes to the performance of this experiment, I found it really interesting and really highlights, I think, something that if you've listened to the show a lot, you've heard me say a lot, which is performance is is completely dependent on the hardware and the underlying software that you're running on top of. And it's really hard to predict what the characteristics of that will be. And generally, pretty much always, the best way to do performance optimizations is to just profile and test your code, not to guess about what's faster. And I think this is another instance of this. I went into this thinking, oh, this will be a really cool way to like have much more efficient code. And it turns out not really. There's more reasons, uh, I think underlying why this is. But I thought it was really interesting that I thought this would be faster, but it really didn't make a big difference. So yeah, really highlights that it's super hard to predict performance. But the cool thing that I didn't expect was the code part that this let me write better code. So yeah, um if you want to, you know, use refs in your own code, I think it's actually a really useful technique. It might be worth exploring, just creating some like throwaway applications to mess around with refs and understand them better so that you can um, you know, figure out when to use them. Um, but yeah, I'd love to hear uh more from all of you. Have you ever messed around with storing state inside refs like this or decoupling state updates from when reactory renders? Or like, do you have any other ideas of how this technique could be useful or other applications for it? Um yeah, I would love to hear from you if you have any uh ideas on that. And speaking of ideas, I think this is a a great time to transition into the uh main part of our episode today, um, which is you know, thinking in React, which I guess to a large extent we've already been doing with this experiment, right? Like this was very in-depth. Like, how does React work? Well, this um thinking in React is more about from a high level. So now we're gonna take a step back and be like, if you're uh new to React, if you're a beginner, you're just like, I'm trying to understand React and what it is, you know, whether you're a new programmer or an experienced programmer, we're gonna take a look at, you know, how do you actually take an idea and convert it into a good React application? How do you think in a way that complements the strengths of React itself? So this is not necessarily an original idea at all. This is um based on the thinking in React section from the React documentation. And the reason why I wanted to make an episode about it is A, because maybe you want to hear about it in a podcast versus read it in the documentation. But B, I actually pretty strongly disagree with one part of the technique that they talk about in the documentation. So I'm gonna talk about why I disagree with that and why I think there's a much better way to do it. Um so we'll get into that a little bit later. So when you think of React, what do you think of? Do you think of components? Do you think of state? Do you think of some person ranting about things on your favorite podcast? I don't know. What do you think about it? Uh to me, I think really about components. I think that's really what is unique and special and the strength of React itself. So to me, React is made of components, but how do we go from an idea or a mock-up or a design to a React application that's made of components? And, you know, how do we do that in a way that works well and produces good results? So, first, I think we need to take a step back and look at what is a component, you know, what should a component be? What should a component be made of? So to me, I think of components as a way of encapsulating behavior andor state so that you can build with it without having to know how it works. It's sort of like Legos that you can combine into larger and larger sets of Legos that can be plugged into each other as you know units. You know, React's primary means of abstraction is this Lego or this component. Like, for example, let's say you have a button that you use throughout your application and you want it to look and behave the same without having to recode it every time, you know, copy and paste this, you know, component and its styles and its behaviors and its animations and whatever it has. You don't want to copy and paste that throughout your application. You know, that's exactly what components enable you to do. They enable you to not copy and paste it, but to encapsulate its looks and behaviors into something that you can just plop into a larger component and utilize. You know, you can create a button component and reuse that component without having to recode it or, and I think even more critically, you know, without having to understand how that button component works internally. If you want to get more into the details of like what makes a component, what is JSX, you know, how does uh component fit into the machinery of React itself and how it renders components, I definitely recommend checking out my book, Foundations of High Performance React, which actually, you know, isn't just about high performance. We start by going through the process of building your own like mini React, including the algorithm React uses for rendering a component. You can um find it on the ReactShow.com if you want to, you know, dive into the details more about the mechanics of components themselves. But when we look at like a higher level, you know, what makes up a component, we also have to look up, you know, take a look at the other major part of components, which is state. You know, what is state and how does it relate to components and even styles? These are things that I think are very tightly tied to components, or at least they should be, if you want to take advantage of the strengths of React. So in the thinking in React documentation, they state that state is the minimal set of changing data that your app needs to remember. And as they point out, this is distinct from computable data. So our state is the data that changes, essentially, whether it's coming from the server or from user interaction or a timer or an animation, even anything that that changes and you can't derive it or compute it from other data within your system. So this is what we mean when we talk about state. But the cool thing is, I think a bit unlike the technique used in the React documentation for the thinking and React concept, the approach that I'm gonna talk about, you don't really need to worry so much about what state actually is or how to set it up. The cool thing is with this approach, it will kind of come out naturally. So before we get into the method that I use to develop React components, I want to talk a little bit more about the Thinking and React section from the React documentation. I think it has the right idea generally, but I believe that part of the method that they're teaching actually leads to really bad design. And we can learn to think and react while building a better design. So the thinking and react documentation takes what I call a top-down approach to design, where you attempt to guess what the design should be from the beginning by trying to essentially take an initial design or mock-up and break it down into components before you ever really start coding. You're taking it from the top, the you know, design, and working down from there and trying to create components out of that. So I really don't like this approach. In my experience, it definitely feels like a natural place to start. And I think when you're new to programming, it just might seem like the natural thing to do. But the problem, I think there's two main problems really, actually, with this. Um, so one is it usually leads to very rigid and non-composable designs with many components that are like really similar to each other but slightly different, which leads to hard-to-maintain code and what I call leaky components, where the internal state or behavior leaks out of the component and infects everything that uses it. So you can't necessarily just drop your components in. You also have to understand how those components work internally. And two, the other reason why I feel like this is a bad approach is that it sets you up to be blocked. And what I mean by that is normally, like, I think people look at this and they're like, oh yeah, this will be great. It'll make it really easy for me to take this design and break it down into components. But what you'll find out if you actually start to do this is that you'll get stuck a lot because without actually doing the coding and understanding internally how things work, it's actually really hard to visualize up front how to design things. And so you'll find yourself being like, Oh, should I make this into different components? Or is this really the same component, but it should take a different prop value? You'll find yourself in this situation over and over again. And I've talked, especially with people that are newer to programming, about this a lot because they'll come to me and they'll be like, I don't know really what to do. Like, should I do it this way or should I do it this way? I just haven't done much work on it because I just I'm not really sure where to go from here, what to do next, how to proceed. And I think this is a major downfall of this top-down design pattern. So I prefer to take what's called the bottom-up design approach, where we extract the design out of the existing code. So I believe this is both faster as you're much less likely to get stuck, and it leads to better design in the long term. The top down approach makes it much harder to see or visualize the actual characteristics of your program, whereas the bottom up approach makes this blatantly clear and obvious. So it's much easier to move forward in a more concrete way. So, next up, I'm gonna teach you via a Top-down method, my very bottom-up way to design. Um, anyways, this is the method that I use to actually write React code, and I have found it to be the most effective. So, first, I always start with the data. So, before I even get into what it really looks like, and sometimes, you know, what it looks like and what the data is, you kind of develop these together so you can understand what the data is. But I really focus on the data first of all. So I just sketch out on paper a bit to get a feel for the data that I'm working with. I don't get fussy necessarily about the details, but I try to understand, you know, any calculations that are involved and what like the true source of my data is, the data that can't be calculated or derived in any way. And if you remember back, this is really what our state is made up of. Um, so I really hone in and I focus on this, and I just try to make sure I'm really familiar with it and I really understand it. After that, I get into the visual aspects of it. What does this look like? So I might sketch this out, you know, on paper. I might rough it out actually in React itself. You know, I might be given a mock-up or a design from a designer. Either way, the next thing I make sure to have is what it should look like. I think it's pretty tough to do a good job at the rest of this if you don't start from there. I think some people try to, I don't think it leads to good results. I really recommend at the very least just sketching out in some way what you want it to look like and kind of how you want the UI itself to behave. Once you've done that, though, this is where I think me and the thinking and react documentation are, you know, generally in alignment. They essentially say similar things with less focus on data and more on the display part, but I think they kind of go, those things kind of go together. But this is where we diverge. So in the thinking and react documentation, they suggest looking at your um mock-up and breaking it down into components. I take a completely opposite approach. I create what I call the one React component to rule them all. It's essentially a static React component with no state, lots of copy and paste, but just one React component. I very explicitly make sure not to spend time abstracting or creating any React components at this stage. I build one giant React component that contains everything I need to recreate the mock-up with some sort of static or fake data. Essentially, I want to recreate the mock-up in React, but I'm not worrying whatsoever about creating new design. So I might reuse existing components that are in my project or components from libraries or hooks, but I'm not creating any of my new components or hooks or anything at this stage. All I do is create this one gigantic React component. And once I get that working and it's on my screen and I can see that it looks like the way I want it to look, then I move into the next step, which is actually making this gigantic React component interactive, making it work essentially. So I'm still focusing and making sure that I'm not abstracting anything yet. I'm just gonna make this work. So your code's gonna look really messy. It's gonna, you know, you'd never want to really submit this for your, you know, final result or anything, but it's really important to start here. And so you'll have a really messy, gigantic component. And I slowly convert that while keeping it compilable and runnable the whole time. I slowly convert my static component into an interactive one. So I start adding new state, I start adding other hooks to track state and events and things like that, and make it function. So initially, I usually make it function with lots of static data, you know, maybe I'll plug into my server at this point and get the data from there. Either way, I'm making it actually function without yet worrying about the design. Now, once I do have it functioning, like I can use it, it's basically a functional mock-up and maybe even uses real data. That is when I start to look at how to break it down into components. But the approach that I take and I recommend you taking is you're not looking at the mock-up or the high-level, like, okay, what you know, how do I break this into a design? You know, what I do is I look through the code itself for patterns, patterns that are repeated three or more times. So I'm not necessarily looking for components or state or anything in particular. I'm just looking for patterns. I'm like, does this seem like a pattern that's repeating itself? And once I identify those patterns, that's when I start actually abstracting things based on the smallest bits of like repeated patterns or code. So, like, for example, let's say I am going through and I've built this one gigantic React component to rule them all. And throughout this gigantic component, I have this, you know, button essentially that I'm using over and over again. And the button has, for the most part, the same styles and the same behavior. And I've just copied and pasted it. So I'm gonna go through this and I'm gonna be like, oh wow, look at this. I have a pattern. What should I do with this pattern? Um, I'm not necessarily gonna make a component from it to start with, but let's say in this case, I'm like, oh yeah, it would make sense that this button becomes its own component. So I just look directly at the code I've already written and I look for the parts of my button code that repeats itself, you know, where I've done a copy and paste. And I only abstract the repeated parts. I don't try to visualize or guess, you know, what my button component should support or should behave in the future. I'm not guessing about future design. I think that leads to that's premature design optimization. It leads to bad design. I purely do it based on the code that I've already written. And this is sort of the critical part that keeps you from getting stuck. You're never like, okay, how do I think people are gonna use this and other ways in the future? You never think about that. You just go, okay, this is how I'm using it. This is the pattern. This is what I'm gonna abstract. It's very straightforward. So yeah, maybe now I create one, you know, button component and I move all of my duplicated button code into this button component and I use that button component in my giant larger component, right? But I don't stop there. I've now created what I call one button to rule them all, you know. This one button though might not be the final answer. So I actually repeat this process over and over again with each part that I abstract. So I look at my button and I'm like, do I have any patterns that are repeating themselves? And, you know, maybe I do. Maybe I'm like, oh, okay, so it seems like I really have two different buttons here with maybe some different styling but similar behavior. Maybe I have a primary button and a secondary button. So I start transforming my one button to rule them all into maybe a primary button and a secondary button. And I do it, you know, in a transformative way so that my application keeps running, I can keep testing it, um, I can keep seeing what the end result is. I'm not making a big refactoring, I'm just transforming my code one step at a time. You know, so now I might break up my one button to rule them all into these two other buttons, and I might now use these two other buttons in my larger component, my you know, primary place where I started working with, right? So now this larger component uses primary buttons and secondary buttons. And then I look at my primary button and my secondary button, and I'm like, hey, are there any repeated patterns here? You know, we just keep repeating this process. And, you know, I might be like, oh, actually, I can see it really clearly now. Everything is repeated except for these styles. You know, one is a blue button and one's a gray button. Okay, well, I can make a generic button component that has everything except the styles. And then my primary button and my secondary button just import this general purpose button while passing in their own styles or specifying their own styles somehow. So now I end up with a primary button component, a secondary button component, and a you know, sort of base button component, right? But I didn't have to really think too hard about it. I just sort of kept looking at my code and going, oh, what is this pattern? How do I make this pattern into some abstraction? Uh, how do I convert it to a component essentially? This sort of prevents you from getting in that stuck state, but also leads to really powerful design patterns. Because what you'll find if you develop this way is that you create a lot more composable components. This transformative process where you're just sort of extracting patterns out of your code will lead to components that are very self-contained, where their behavior and their state live inside the button, and you can just drop these buttons in other places without having to work at it or understand you know how they're implemented internally. And I focus a lot on this. So I might take my you know button component and I look at it and I go, okay, am I exposing anything that's internal to this button that I don't need to? Am I like sharing the state of whether the button is depressed or not depressed with the outside world? Do I need to share that state? You know? Um, probably not. So that should be inside to this component so that if I use this component, I don't need to know that it's tracking that or not tracking it. I don't need to care. So I focus really heavily on what does this interface look like between my new component and everything else? Am I encapsulating all of the behavior and the styles and everything inside of this component so that anyone can use this component and they don't really need to know how to use it correctly. If you ever find yourself writing code where uh you're like, okay, if I use this code somewhere else, I just need to remember, you know, maybe write a note for myself or whatever in the comments. Oh, remember, only use it this way. Don't use it this way. That's a uh code smelt, basically saying your abstraction is leaking. And that's not what we want. But if you use this transformative process and you use it with this analytical view, I believe what you'll find is that you create really well-encapsulated components. And going back to the high level of how do we think in React, this is really how we do it. We create composable components. React is really good at components. So learning how to practice and um think in terms of components is really the key to thinking in terms of React. All right, so we've gotten into the weeds a bit. Let's uh, I think, step back and just take a look at the process itself. So, what I do is I create gigantic components, then I look for patterns, then I abstract those patterns, and I just do it in a transformative process where I'm never really creating um new behavior or new functionality. I'm just taking what's there and better abstracting it. And I do this in a repeated fashion. So I just do it over and over again until I don't find any more of these repeated patterns. And it always starts out very messy and, you know, not great code. But what I do throughout this transformative process is just keep refining it and keep refining it. And you can stop whenever you want. You're you can be like, oh yeah, this is good enough for now. I'm gonna, you know, maybe do this again later, or maybe I'm just gonna leave it as is. Um, this allows you to spend as little or as much time as you want on design. And you can always go back and do this process over and over again and make it even better designed, but it's not trying to do all the design up front. So this is really important. I don't take big leaps, I don't try to create fancy design up front. I just move code around from the larger component or hook into smaller ones, or even back and forth between them. I'm just sort of using this as a sandbox where I play around and I go, okay, this is a pattern. Let me try some different ways of abstracting this pattern. Which, you know, abstraction do I like better, which one works better, which one makes more sense, which one fits better into my program? I just keep doing this in a very transformative, um, sort of prototypical fashion, you know, where I'm playing around with it, seeing how it works, seeing, and the whole time maintaining this working larger program. That's actually my entire process for thinking in React and creating good React programs. It's all about taking and analyzing patterns and extracting those patterns into components or hooks. That's what React is good at. That's our goal. We want to make things into encapsulated hooks and components. And eventually you won't have one giant, you might have one, you know, top-level component. So it's made of a lot of these smaller, more organic components. Um, but that's the transformative process that I have found works the best. So, just as a review, the way that I think and React is to start with, I don't really think in React. I just write code. I just make one gigantic, ugly component, and then I iterate on it over and over again, looking for patterns, extracting those patterns into components. And as you do this more, I'm sure you'll get better at it. But I think this is the best place to start when it comes to thinking in React. It's not so much about top-level, you know, trying to create components out of thin air. It's about looking at what you've already written and just converting it and transforming it. And then our goal with these transformations is always to utilize the strengths of React, which is components. How do we create components that encapsulate everything inside of them in a nice clean manner? That's really my goal and my entire process of thinking in React. Now, if you want to dive into more of the details and the internals of how React works and you know how you can maybe take advantage of other aspects of it, that's certainly something that you can do as you get more experience. But in terms of actually just creating real React applications that work well, I have found this to be the best method. And this is what I use and what I've taught a lot of other people to use, and they seem to have agreed with me. I think what I've I've noticed sort of over time is that this is kind of hard for people to do. I've worked with a lot of people where we've gone through this and and they've utilized this method, and they're like, oh wow, this is so much better. I don't get stuck anymore. And then like two weeks later, they come back to me and they're like, oh, I got stuck. And I'm like, oh, okay. You know, can you show me where you're at? Show me what you're doing. Well, it turns out they sort of reverted back to the top-down approach and they were trying to create abstractions without writing the code first or understanding the code first. And I think this is maybe it's maybe a natural way to think about it. But in my experience, it isn't the best way to do it. So, you know, don't feel bad if you you sort of revert to that previous pattern. I think it's very natural. Um, but I think this definitely pays off. And if you get stuck, that's probably sort of a clue. Like, oh, maybe I'm not trying to transform my existent code anymore. Maybe I'm trying to design out of thin air. Yeah. So that's my advice is if you do go down this path, something to be aware of. It's maybe not as intuitive or easy to start with, but I think if you just don't, you know, get too tangled in it, if you just take a very straightforward approach and just focus on your code and transforming it, it should be pretty simple and easy to do. And in my experience, leads to really good results. Anyways, that's my method. That's what I do. I hope that helps you learn to think and react as well and create good React applications. But I'm really curious, you know, is this how you think and react? Do you have a better method? You know, what do components mean to you? You know, I would love to hear from you if you, you know, have any other ideas. You know, feel free to message us onreact show.com, tweet at us any way you'd like to get in contact. I would love to hear more. Um, I'd love to hear what you think of this approach. Do you think it's a terrible approach? Are you like, no, I've tried this, it doesn't work. Anyway, I'd love to hear because you know, um, I always like to learn and get better as well. Anyways, yeah, thank you once again for joining us. This episode was produced by Thomas and edited by Dougie, the podcast editor.