A note about not firing side effects in useState(prev => next) ?
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- JavaScript
- Sterne
- 11.8k
- Forks
- 7.9k
- Ø Merge
- 1 T. 11 Std.
- Gemergte PRs (30 T.)
- 11
Beschreibung
So I ended up doing this by mistake after a wonky merge:
let Foo = (props) => {
let [bar, setBar] = useState();
let handleClick = () => {
useState(bar => {
let newBar = bar + 1;
props.handleBarChange(newBar); // bad, which isn't surprising
return newBar;
});
};
return <div onClick={handleClick}>click me</div>;
};
If you fire a side effect such as calling something that sets state in a higher component from a useState updater function, you get the error "Cannot update a component from inside the function body of a different component" (but not always! It seems to depend on internal timing). This definitely seems like a bad idea when you look at it, but I couldn't find any mention in the docs that this is bad.
https://reactjs.org/docs/hooks-reference.html#functional-updates
There is the note about side effects generally on useEffect:
Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase)
But this is not in the main body of a function component, doesn't feel like a true side effect as it's still just setting state within React, and doesn't feel like it's in the render phase either.
I initially wanted to comment about this here (https://github.com/facebook/react/issues/18178), because the general message of that thread was "don't set state of another component in a render method", and I've managed to get this error message without doing that, but the thread is locked. Thanks.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der verlinkten Hooks-Referenzseite, insbesondere dem Abschnitt zu funktionalen Updates, und vergleiche deren Hinweise mit dem zitierten Hinweis zu Nebenwirkungen von useEffect. Kläre, ob Nebenwirkungen innerhalb eines useState-Updaters nicht unterstützt werden, und erläutere das relevante Verhalten; als erledigt gilt dies, wenn die Dokumentation dieses Beispiel ohne Mehrdeutigkeit behandelt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript, react
- Bereich
- documentation
- Issue-Typ
- Dokumentation
- Schwierigkeit
- 2/5
- Geschätzter Aufwand
- 1-3 Stunden
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100