Browse Source

[Beta] You Might Not Need an Effect (#4766)

main
dan 3 years ago
committed by GitHub
parent
commit
5187ed6bbd
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      beta/src/pages/apis/usestate.md
  2. 1635
      beta/src/pages/learn/you-might-not-need-an-effect.md
  3. 4
      beta/src/sidebarLearn.json

2
beta/src/pages/apis/usestate.md

@ -1078,7 +1078,7 @@ button { margin-bottom: 10px; }
Note that if you call a `set` function while rendering, it must be inside a condition like `prevCount !== count`, and there must be a call like `setPrevCount(count)` inside of the condition. Otherwise, your component would re-render in a loop until it crashes. Also, you can only update the state of the *currently rendering* component like this. Calling the `set` function of *another* component during rendering is an error. Finally, your `set` call should still [update state without mutation](#updating-objects-and-arrays-in-state) -- this special case doesn't mean you can break other rules of [pure functions](/learn/keeping-components-pure).
This pattern can be hard to understand and is usually best avoided. However, it's better than updating state in an effect. When you call the `set` function during render, React will re-render that component immediately after your component exits with a `return` statement, and before rendering the children. This way, children don't need to render twice. The rest of your component function will still execute (and the result will be thrown away), but if your condition is below all the calls to Hooks, you may add `return null` inside it to restart rendering earlier.
This pattern can be hard to understand and is usually best avoided. However, it's better than updating state in an effect. When you call the `set` function during render, React will re-render that component immediately after your component exits with a `return` statement, and before rendering the children. This way, children don't need to render twice. The rest of your component function will still execute (and the result will be thrown away), but if your condition is below all the calls to Hooks, you may add an early `return;` inside it to restart rendering earlier.
---

1635
beta/src/pages/learn/you-might-not-need-an-effect.md

File diff suppressed because it is too large

4
beta/src/sidebarLearn.json

@ -166,6 +166,10 @@
{
"title": "Synchronizing with Effects",
"path": "/learn/synchronizing-with-effects"
},
{
"title": "You Might Not Need an Effect",
"path": "/learn/you-might-not-need-an-effect"
}
]
}

Loading…
Cancel
Save