Yesterday, we made a button. Out, it turns white, and when you click it. That when you hover over it, there’s red. And I mentioned that in an architecture with multiple components that have to talk to each other, you make it so that props go down and callbacks come back up.
In your react, we always try to use what’s called a unidirectional link. You have your state somewhere up top, and this state flows down via props into your vews, which use it to render stuff. And these vews trigger actions, or callbacks, which go back into your states. So these are callbacks. You keep your state in a central place, where everyone can access it, anyone who actually needs that state. And your vews only take care of rendering from props, try to avoid local state and vews, and those vews trigger callbacks that then have to go back up to state to change anything.
Now let’s take our button from yesterday. It starts as a normal rectangle. When you hover over it, it becomes a red rectangle, right? That works great as local state in the component. Our callback goes directly to the button. Now let’s say we have another component next to our button. Let’s say this is a related comment, so this could be a delete button, and it needs to highlight what it’s deleting, which is this comment over here. Now both of these components need to know whether the button was hovered, which means local state is no longer going to be enough.
So we hoist this state up, into a common component. We’re just calling it “state” so far. But this component needs to know whether the button is hovered. Now what happens, is both of these get their props, that say, “Hey, this is in a hovered state.” When we hover over this button, it needs to fire a callback back up to this state. And when that happens, this state changes, triggers a re-render of all the children and sends information down to our hovered component. And they both turn red.
It’s easy to get carried away. People often put too much stuff into their global state. You should always try to have state in as low a component as possible. Keep it as localized as you can, because otherwise, you end up with these huge state trees that are very difficult to maintain, and very difficult to control.
Tomorrow, I’m going to show you how this looks in actual code, and we’re going to build something with these buttons and related components. And then the day after that, we’re going to look at the new context tab-
Know someone who wants to learn React and its whole ecosystem? Share 👇