React: State & Props — IRL
Drawing and thinking about programming concepts as real objects in the world is helpful to me when trying to learn new concepts. This is an analogy I have pieced together to understand the behavior of state and props of React in a physical space.
React, Inc. is a new company.
When it is first founded, it’s an empty building.
However, it quickly grows to have multiple functioning departments, each with their own employees. It becomes a very oppressive place to work.
In this model, props are represented by information within the company (sales records, new products, customer data, company policies). In programming, they can be just as varied — strings, arrays, numbers, functions, etc.
Since props can only be passed down from their parent components, the company always owns all of that information, but they need to be able to give it to the departments for them to do their jobs properly.
This one-way communication is represented by a loudspeaker on the wall of each of the departments. The company can pass information to the department through this speaker, but there’s no way for them to respond.
Employees all wear headphones, so they can’t hear the information coming into their department. However, the department can pass them information through these headphones (if they need to).
The headphones do not have a microphone, so the employees can’t speak back, even if they wanted to.
However, they still all need to work together to get their jobs done. The only way they can pass information back and forth to each other is through state.
When the ReactDOM loads, each component (in this case, the company, each department, each employee, and anything below that) will render, and then become static. State is data that can be mutated in each component. In order to interact with these static components, the state of each can be changed.
Each time the state changes, that component is re-rendered. However, everything else stays in its previous static form.
In the company analogy:
The sales team needs to know what the new company logo will look like, so they can start using it on their marketing materials. The art department will provide the color palette to select from, and inform the company of what was selected.
Ultimately, the art department provides the color options, the company carries the selection, and the sales department creates its materials with them, bringing the whole organization into harmony. Just like React IRL.