React101: State Management

Previously in the React101 series, I covered JSX, Components, Props, and Hooks. In this section, I have shared examples using all of them together.
Note: These examples are taken from the “Learn React” Scrimba course.
Example1 — Flipping State back and forth
Clicking on the div.state — value flips the state from true to false and the value “Yes” to “No”. Here, the prev state value is required to give the new value.
Example2 — Complex State: Arrays
This example explains updating a list of items of an Array using State. The setter function to update state can be used in 2 ways: directly updating the array or using a callback function.
The best practice is to use a callback function, so that it gives access to previous state to update the new array of values.
Example3 — Complex State: Objects
This example explains how to update the state when it is an object.
Always remember to copy the previous object and then change the value of the required field.
Challenge — Objects in State
The following example has a bug, the input values disappear on typing different input. How is this fixed and what else is missing to make the code function?
Example 4 — Passing State as Props and updating from Child components
In the following example, setting the favorite state is updated from the child component. This example shows how the child component gets the ability to change the state that lives in the parent component.
Passing Data Around
In React, data is passed using props. In the above example, the favorite star feature was extracted to its own component, and the state was changed by the handler that was passed to the child. In a scenario, if a parent has two child components, and both child components need access to data, then data is passed only via the parent. One child component cannot pass data to another child component.
As depicted in the diagram below, passing data is uni-directional from parent to child.
In a more complex structure, state management libraries like Redux, context is used to avoid the hierarchical passing of data.

State Changes: Local v/s unified
What happens when child components want to change the state value?

In the above screenshot, there are 5 boxes defined in the App component and their state: true/false is passed to the individual Box components and based on that value color is rendered for the box which would appear as below:

If each box wants to change its color, it defines its own state variable and initializes it to the value received as props from the parent component, and uses the setter function to change the value.
This state is called- Derived State. You can read more to find out when and when not to use it.
In the below diagram, the toggle function is defined in the App component itself and then passed on to the Box components with their id to toggle the state and change the color of the box.

The code-sandbox code snippets explain how this is achieved.