Calling state setter with same value doesn't reliably work as documented
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
Thank you for the very high standard of documentation on the React website.
There's a bit that's slightly misleading, though. The "functional updates" section of the useState documentation says:
If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely.
However, if you watch calls to the component function doing the state update, it seems like a render occurs the first time you do that, because the component function gets called that first time. (Once it returns a bail-out means child components aren't called to rerender.) Subsequent times the component sets the same state value, even the component function isn't called (because of a separate "fast" bail-out).
That first time looks like a render to a dev who's read the documentation and expected setting the same value to be a no-op. That's confusing enough to have made @amsterdamharu file this closed bug report and to have made me, independently, come to github to write a bug report as well (but fortunately I found that one first).
Perhaps:
If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely (although the component function may be called, at least the first time).
...or something like that.
Then when developers see our component function get called even though we did setValue((v) => v);, we'll know it isn't a bug or our misunderstanding something; it's just part of the complexity of React (and there's probably a good reason for it).
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
Beginnen Sie mit dem verlinkten Abschnitt „functional updates“ der useState-Dokumentation und überprüfen Sie die Aussage zu identischen Zustandswerten. Aktualisieren Sie die Formulierung, um zu erklären, dass die Komponentenfunktion beim ersten Update auf denselben Wert aufgerufen werden kann, während das anschließende erneute Rendern übersprungen wird; die Änderung ist abgeschlossen, wenn die Dokumentation nicht mehr impliziert, dass die Funktion immer ein no-op ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript, react
- Bereich
- documentation
- Issue-Typ
- Dokumentation
- Schwierigkeit
- 1/5
- Geschätzter Aufwand
- Unter einer Stunde
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 68/100