How states work with UI
With the introduction of state to the function component, we sometimes can get dizzy by the roles that it plays. We will use three components to elaborate, as shown in Figure 2.11:
We have three components depicted in solid boxes. The outer component contains the middle one as a child, and the middle one contains the inner one as a child. Props, depicted as arrow lines crossing the boundary of a solid box, pass values from a parent to a child component.
React is a state machine. For a given fixed set of variables, it paints the screen the same way. With props, this is quite straightforward since each component is solely determined by its props. Now, let's add the states to the picture, as shown in Figure 2.12. States, depicted as a symbol with a circle and a dot, are defined inside each component:
Taking the C inner component first, it doesn't have any state defined. So, it's still determined by its props.
The B middle component has one state defined. With a fixed set of its props, the screen corresponding to the component still can vary because this state can take a different value on each update.
The A outer component has two states defined. Similarly, with all its props fixed, the screen corresponding to it can still vary. The variation can come from any of its two states, and it can come from the state of the B component as well because the states of the parent and the child can work independently upon updates.
Therefore, we can conclude that to get the screen painted for the A component, we need to fix all props and states within itself and all its child components underneath. This is not a mathematical theory, but given the states from multiple components, this observation is apparent.
In short, props and states now both serve as the input of the component. The states can be especially vibrant since their values can be, but are not always, wired with an external system. The external system can be browser events or the API fetch, or anything else. Because a state can send to a child component via a prop, the effect of the state can cascade down deep into the app tree quickly.