@@ -36,14 +36,15 @@ Adding Interactivity
36
36
:link: state-as-a-snapshot
37
37
:link-type: doc
38
38
39
- Learn why IDOM does not change component state the moment it is set, but
40
- instead schedules a re-render .
39
+ Learn why state updates schedules a re-render, instead of being applied
40
+ immediately .
41
41
42
42
.. grid-item-card :: :octicon:`versions` Multiple State Updates
43
43
:link: multiple-state-updates
44
44
:link-type: doc
45
45
46
- Under construction 🚧
46
+ Learn how updates to a components state can be batched, or applied
47
+ incrementally.
47
48
48
49
.. grid-item-card :: :octicon:`issue-opened` Dangers of Mutability
49
50
:link: dangers-of-mutability
@@ -147,12 +148,31 @@ snapshot.
147
148
:octicon: `book ` Read More
148
149
^^^^^^^^^^^^^^^^^^^^^^^^^
149
150
150
- Learn why IDOM does not change component state the moment it is set, but instead
151
- schedules a re-render.
151
+ Learn why state updates schedules a re-render, instead of being applied immediately.
152
152
153
153
154
154
Section 4: Multiple State Updates
155
- ------------------------------------
155
+ ---------------------------------
156
+
157
+ As we saw in an earlier example, :ref: `setting state triggers renders `. In other words,
158
+ changes to state only take effect in the next render, not in the current one. Further,
159
+ changes to state are batched, calling a particular state setter 3 times won't trigger 3
160
+ renders, it will only trigger 1. This means that multiple state assignments are batched
161
+ - so long as the event handler is synchronous (i.e. the event handler is not an
162
+ ``async `` function), IDOM waits until all the code in an event handler has run before
163
+ processing state and starting the next render:
164
+
165
+ .. idom :: _examples/set_color_3_times
166
+
167
+ Sometimes though, you need to update a state variable more than once before the next
168
+ render. In these cases, instead of having updates batched, you instead want them to be
169
+ applied incrementally. That is, the next update can be made to depend on the prior one.
170
+ To accomplish this, instead of passing the next state value directly (e.g.
171
+ ``set_state(new_state) ``), we may pass an **"updater function" ** of the form
172
+ ``compute_new_state(old_state) `` to the state setter (e.g.
173
+ ``set_state(compute_new_state) ``):
174
+
175
+ .. idom :: _examples/set_state_function
156
176
157
177
.. card ::
158
178
:link: multiple-state-updates
@@ -161,7 +181,7 @@ Section 4: Multiple State Updates
161
181
:octicon: `book ` Read More
162
182
^^^^^^^^^^^^^^^^^^^^^^^^^
163
183
164
- .. .
184
+ Learn how updates to a components state can be batched, or applied incrementally .
165
185
166
186
167
187
Section 5: Dangers of Mutability
0 commit comments