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

This commit is contained in:
dan
2022-06-22 23:15:15 +01:00
committed by GitHub
parent f71c82fcd4
commit 5187ed6bbd
3 changed files with 1640 additions and 1 deletions

View File

@@ -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.
---

File diff suppressed because it is too large Load Diff

View File

@@ -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"
}
]
}