mirror of
https://github.com/reactjs/react.dev.git
synced 2026-02-24 04:33:10 +00:00
[Beta] You Might Not Need an Effect (#4766)
This commit is contained in:
@@ -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
Normal file
1635
beta/src/pages/learn/you-might-not-need-an-effect.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user