Many loopsLesson 19 of 23

What happens when there are two?

Render a component twice and see that each keeps its own state.

One counter is a Model, some messages and an update. This screen has two of them, one for apples and one for pears, and a parent that draws both.

Predict

Read App.ts and Counter.ts before you touch anything. Press + on Apples in your head. Does Pears change? Find where each count is stored before you answer.

Check your answer

No. App has an empty Model, so the counts aren't there. Each Counter(h, { ... }) in the parent's view declares one instance of the component, and every instance has a Model of its own, started by its own init.

Try it

  1. Press + on both counters and read the log. Each row now ends in a path, such as Counter[apples]. Whose update ran for each row? Did App receive anything?

  2. Declare a third counter in App.ts with the key "eggs" and the label "Eggs". Before you run: what does it start from, and who decided that?

  3. Eggs come by the dozen. In Counter.ts, add step: Schema.Number to props and use $.props.step in both handlers in place of 1. Show it on the buttons with h.props.step. Then pass step: 1 to apples and pears and step: 12 to eggs.

  4. The parent now decides each counter's step. Can it also set a counter's count? Look for a way before you open the answer.

About step 4

It can't. A parent gives a child props and nothing else. It has no handle on the child's Model and no way to send the child a message. When a prop changes the child is drawn again, and its next update reads the new value from $.props.

The key is what makes that safe. It names the instance, which is how the runtime knows from one drawing to the next which Model belongs to which child.

What you found

Calling a component with the parent's h declares a child. Each child is the whole loop from the earlier lessons: its own Model, its own messages, and its own fold of them. That is why the log needs paths now. It is one list, and each row belongs to one instance.

The parent's reach stops at props. A message goes straight to the update of its own instance, and nothing else runs. So you can read Counter.ts alone and know everything that can change a count.

Props travel one way, down. A counter with a Remove button has a problem, because the list of counters isn't its to change. How does a child talk back?

19
Principle 19

Every component is its own loop

A component owns its Model, its messages and its update. Rendering it twice gives two independent loops, told apart by a key.

ResultStarting

No messages yet

Use the example above. Each message that reaches update shows here, with what it changed.