Open3

コードを読んで React Fiber を学ぶ

tomoeinetomoeine

コードを読んで ReactFiber を学ぼうと思ったけど、ReactFiber とついたコードが多すぎて、どこから読んだらいいのやら・・・

Claude に聞いたところ、

エントリーポイント:
まず、packages/react-reconciler/src/ReactFiberWorkLoop.js から始めるのがよいでしょう。

ということ。

さらに、レンダリングはどこからスタートするのか聞くと

同期レンダリングの場合: renderRootSync
並行(Concurrent)レンダリングの場合: renderRootConcurrent

ということ。

↓フローについて、Claude3 が生成してくれた UML

tomoeinetomoeine

どんなときに同期レンダリングでどんなときに Concurrent レンダリングになるの?
という疑問があったのでちょっと寄り道。
基本的には Concurrent で、特定の処理( onSubmitonClick 等のイベントハンドラ、 ReactDOM.render() を呼び出した場合など)で同期レンダリングが発生するらしい。

Concurrent が基本ということだったので、 renderRootConcurrent を見ていく。

tomoeinetomoeine

renderRootConcurrent を読む。
200行以上あるメソッドなので、主要な処理から順番に・・・

function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
  // ...
  // Fiber 単位でのループ
  outer: do {
    try {
      if (
        workInProgressSuspendedReason !== NotSuspended &&
        workInProgress !== null
      ) {
          // ループが終了判定された際の処理
          // 条件によって outer ループを終了 or 例外を投げる
      }
      // この中で workInProgress な Fiber を処理&次のFiberに進めている
      workLoopConcurrent();
    } while (true);


  if (workInProgress !== null) {
    // 未処理の Fiber が残っている
    // ...
    return RootInProgress;
  } else {
    // 全ての Fiber に対して処理が終了した
    // ...
    return workInProgressRootExitStatus;
  }