You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -236,3 +237,62 @@ There are two ways to go about this:
236
237
2. Ask `scalajs-react` for an interface that performs the side-effects directly instead of returning `Callback`s. See https://japgolly.github.io/scalajs-react/#examples/websockets for a demo.
237
238
238
239
Reminder: You should never do this in a React context.
240
+
241
+
242
+
Common Mistakes
243
+
===============
244
+
245
+
***Executing instead of composing.**
246
+
247
+
Callbacks must do nothing when you first create them; React might never even call them.
248
+
If you call `.runNow()` when you're creating a `Callback` that's a bug because you're forcing a one-time execution during construction.
249
+
250
+
If fact, even the `{` in `def increment(): Callback = {` is a code-smell. Either use `(` or nothing at all.
251
+
252
+
BROKEN:
253
+
```scala
254
+
defincrement():Callback= {
255
+
$.modState(_ +1).runNow()
256
+
Callback.log("Incremented count by 1")
257
+
}
258
+
```
259
+
260
+
FIXED:
261
+
```scala
262
+
valincrement:Callback=
263
+
$.modState(_ +1) >>
264
+
Callback.log("Incremented count by 1")
265
+
```
266
+
267
+
***Side-effects (especially accessing mutable state) during construction**
268
+
269
+
Callbacks must be repeatable.
270
+
If you perform a side-effect during construction then it happens exactly once (instead of repeatedly) and at the wrong time (construction instead of callback execution).
271
+
If during construction, you read mutable state like a global variable then it is read exactly once and at the wrong time too, which will give the impression at runtime that the state is never updated.
272
+
273
+
Make sure anything impure is *inside* the callback.
0 commit comments