Calling state setter with same value doesn't reliably work as documented
Nessuno ha ancora preso questa issue.
- Lingua principale
- JavaScript
- Stelle
- 11.8k
- Fork
- 7.9k
- Merge medio
- 1g 11h
- PR unite (30g)
- 11
Descrizione
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.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia dalla sezione “functional updates” della documentazione collegata di useState e rivedi l’affermazione sui valori di stato identici. Aggiorna la formulazione per spiegare che la funzione del componente può essere chiamata al primo aggiornamento allo stesso valore, mentre il rerender successivo viene saltato; la modifica è completata quando la documentazione non implica più che la funzione sia sempre un no-op.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, react
- Ambito
- documentation
- Tipo di issue
- Documentazione
- Difficoltà
- 1/5
- Tempo stimato
- Meno di un'ora
- Stato di attività
- Ferma
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 68/100