reactjs / reactjs/react.dev

Request for clarification: can ref initialization code (lazy or not) contain side effects?

Aperta
#7,970 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
JavaScript
Stelle
11.8k
Fork
7.9k
Merge medio
1g 11h
PR unite (30g)
11

Descrizione

New docs on avoiding recreating ref contents has two examples:

Example1:

const playerRef = useRef(new VideoPlayer());

Example2:

const playerRef = useRef(null);
if (playerRef.current === null) {
  playerRef.current = new VideoPlayer();
}

Even the old docs have similar examples:

Example3:

const ref = useRef(new IntersectionObserver(onIntersect));

Example4:

const ref = useRef(null);
if (ref.current === null) {
   ref.current = new IntersectionObserver(onIntersect);
}

Both new VideoPlayer() and new IntersectionObserver(onIntersect) look like calls that might contain side effects inside.
My question is it allowed in any of the above examples, for these calls to contain side effects?

  • imho in Examples 1/3 they should not because they are executed on each render; although only values from initial render are kept.

  • But examples 2/4 suggest a pattern which make reading and writing to refs ok - which normally is an impure operation already. So I thought maybe in those examples at least, it is ok for new VideoPlayer() and new IntersectionObserver(onIntersect) to contain side effects?

It would be helpful if the docs clarified this.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con la sezione attuale su useRef, “avoiding recreating the ref contents”, e con la sezione collegata della Legacy Hooks FAQ sulla creazione lazy di oggetti costosi. Confronta tutti e quattro gli esempi e verifica le indicazioni di React sugli effetti collaterali durante il rendering. Il lavoro è completato quando la documentazione spiega chiaramente se questi pattern di inizializzazione possono contenere effetti collaterali e distingue il loro comportamento.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
javascript, react
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
42/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.