reactjs / reactjs/react.dev

[Suggestion]: Adding documentation to note that Effects in children components are committed before their parent component

Aperta
#7,748 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Summary

Adding documentation to the useEffect page to note that Effects in children components are committed before their parent component

Page

https://react.dev/reference/react/useEffect

Details

Hi

I was digging into React internals and learning how it works under the hood. I came across an interesting behaviour in Effects -- where the Effects in children components are committed before their parent component.

For example:

function Parent({ children }) {
  useEffect(() => {
    console.log("Parent committed effect");
  }, []);

  return <div>{children}</div>;
}

function Child() {
  useEffect(() => {
    console.log("Child committed effect");
  }, []);

  return <p>Child</p>;
}

export default function App() {
  return (
      <Parent>
        <Child />
      </Parent>
  );
}

The result in the console will be

Child committed effect
Parent committed effect

(I made a small animation describing the traversal)

Image

I understand that it is due to how React traverses the Fiber tree during the Commit phase (recursivelyTraversePassiveMountEffects), but it seems like it does confuse some people in

This is not a bug, but I think it would be helpful to have this documented, perhaps in the Caveats or the Troubleshooting section to avoid confusion around this "unexpected behaviour".

What do you think? :)

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 pagina di riferimento di useEffect, in particolare con le sezioni Caveats e Troubleshooting, quindi esamina il traversal collegato di ReactFiberCommitWork.js per avere il contesto. Il lavoro è completato quando la pagina documenta chiaramente che gli Effects figli vengono committed prima degli Effects genitori, usando l’esempio riportato ed evitando qualsiasi implicazione che questo comportamento sia un bug.

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

Valutazione

Stack tecnologico
javascript, react
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
50/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.