react-reconcilerfibertagstateNodememoizedStatealternate

React · Dive 04 of 14

From element to fiber

The filing cards in the planning office

An element is thrown away on every render, so something else has to last. That is the fiber: one mutable object per position in the tree, holding the state, the DOM node, the pending work and a pointer to its other version. Two facts about its shape explain most of what React can do: children are reached by pointers, so rendering can pause, and every fiber has a twin, so React can build the next tree without touching the one on screen.

13 scenes · ←/→ to move
$$typeoftypekeyrefpropselementone render, then the binfibermemoizedStatestateNodelanes · childLanesreturn · childsiblingalternatefiberkept, render after render

React 04 · 1 of 14

The slip is thrown away; the card stays

Dive 03 ended with the element: a five-field slip of paper describing what should be on screen, written fresh on every render and thrown away after. That is fine for a description. It is no good for anything that has to last.

React needs to keep state between renders, find the same DOM node again, know where work is still waiting, and remember where a paused render stopped. None of that can live on a slip that goes in the bin every time.

So the planning office, react-reconciler, keeps a filing card for every position in the town: the fiber. It is created once, by the reconciler, and then mutated in place render after render. The slip says what is wanted now; the card remembers what is there.

The field names show the relationship. pendingProps is the props from the newest slip. memoizedProps is the props that produced what is on screen. Comparing the two is how React knows something changed.

The ideaThe element describes; the fiber remembers

From the source
The slip and the card
ElementFiber
Lifetimeone renderpersists across renders, mutated in place
Created byjsx(), in your codecreateFiberFromElement, in the reconciler
Knows parent and siblingsnoreturn, child, sibling
Holds statenomemoizedState (the hooks list, or class state)
Holds the DOM nodenostateNode
Knows there is work to donolanes, childLanes, flags, subtreeFlags
FiberNode · ReactFiber.js// InstancetagkeyelementTypetypestateNode// FiberreturnchildsiblingpendingPropsmemoizedPropsmemoizedStateupdateQueuedependencies// EffectsflagssubtreeFlagsdeletionslaneschildLanesalternate← your hooks livein memoizedState

React 04 · 2 of 14

What is written on the card

The card is made by a constructor, FiberNode, in ReactFiber.js. It sorts its own fields under three comments: // Instance, // Fiber and // Effects.

Instance: tag says which kind of card this is, key is the key from the slip, and stateNode is what the card stands for in the real world: the DOM node, the class instance, or the root. There are two types. elementType is whatever the slip carried, a memo or lazy wrapper included. type is the resolved value to actually call: null for a lazy component until it loads. Reconciliation compares elementType.

Fiber: the three strings to other cards (return, child, sibling), then the inputs and outputs: pendingProps, memoizedProps, updateQueue, memoizedState (your hooks live here), dependencies (the contexts this card reads) and mode, inherited from the parent.

Effects: flags and subtreeFlags say what commit must do here and below, lanes and childLanes say where work is waiting, and alternate points at the card’s twin. Each of these gets a scene of its own.

One more thing about this card: it is a record, not an object with behaviour. A five-point comment after the constructor says no instance methods, no instanceof Fiber, easy to turn into an object literal, easy to port to a C struct. The file follows through: createFiberImplObject is a second, object-literal version behind the enableObjectFiber flag.

The ideaA fiber is a record with a fixed layout, written in JavaScript

From the source
FiberNode, with the profiler and DEV fields left out and the comments on the right added by usReactFiber.js:134–207 ↗
function FiberNode(tag, pendingProps, key, mode) {
  // Instance
  this.tag = tag;                  // which KIND of node
  this.key = key;
  this.elementType = null;         // what the element said the type was
  this.type = null;                // the resolved type
  this.stateNode = null;           // the DOM node / class instance / root

  // Fiber
  this.return = null;              // parent
  this.child = null;               // FIRST child only
  this.sibling = null;             // next sibling
  this.index = 0;
  this.ref = null;
  this.refCleanup = null;
  this.pendingProps = pendingProps;  // props coming in this render
  this.memoizedProps = null;         // props that produced the current output
  this.updateQueue = null;           // queued updates & effects
  this.memoizedState = null;         // the hooks list, or class state
  this.dependencies = null;          // contexts this fiber reads
  this.mode = mode;                  // inherited from the parent

  // Effects
  this.flags = NoFlags;              // what commit must do HERE
  this.subtreeFlags = NoFlags;       // …and whether it must descend at all
  this.deletions = null;             // children removed this render
  this.lanes = NoLanes;              // pending work on this fiber
  this.childLanes = NoLanes;         // pending work somewhere below
  this.alternate = null;             // the other version of this fiber
}
The rules for this type, in the comment right after itReactFiber.js:209–221 ↗
// This is a constructor function, rather than a POJO constructor, still
// please ensure we do the following:
// 1) Nobody should add any instance methods on this. …
// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
//    always know when it is a fiber.
// 3) We might want to experiment with using numeric keys since they are easier
//    to optimize in a non-JIT environment.
// 4) We can easily go from a constructor to a createFiber object literal if that
//    is faster.
// 5) It should be easy to port this to a C struct and keep a C implementation
//    compatible.
AppHeaderListFooterRow ARow Bchild (first only)siblingreturn

React 04 · 3 of 14

Three strings instead of a stack of open drawers

Until version 16, React rendered by recursion: a function called itself for each child, and each call was like opening one more drawer and leaving it open. A recursive walk keeps its place in the JavaScript call stack, and a call stack cannot be paused. You run it to the end, or you throw everything away.

Fiber ties the cards together with three strings instead. A parent points at its first child only, through child. Every other child is reached from the one before it, through sibling. And every card points back to its parent, through return.

The Fiber type’s own comment says return is “conceptually the same as the return address of a stack frame”. That is exactly the idea: React builds its own stack out of objects on the heap. A stack made of data can be put down in the middle and picked up later, which a real call stack cannot.

The ideaThe call stack became data, so it can be paused

From the source
The comment on return, in the Fiber typeReactInternalTypes.js:122–126 ↗
// The Fiber to return to after finishing processing this one.
// This is effectively the parent, but there can be multiple parents (two)
// so this is only the parent of the thing we're currently processing.
// It is conceptually the same as the return address of a stack frame.
return: Fiber | null,
Our tree from the drawing, as stringsOur example, not from the source
App.child      = Header
Header.sibling = List
List.sibling   = Footer
List.child     = RowA
RowA.sibling   = RowB
RowB.return    = List     // and every other card points back up the same way
AppHeaderListFooterRow ARow BworkInProgressyieldone variable holds the whole position

React 04 · 4 of 14

One finger on one card

With the cards tied by strings, walking the tree becomes a flat loop with one cursor, like a clerk keeping a finger on the card in hand. That cursor is a module-level variable in ReactFiberWorkLoop.js called workInProgress.

performUnitOfWork does one card. It calls beginWork on it, which returns the next card to visit, usually the first child. If there is one, the finger moves there. If there is none, completeUnitOfWork finishes this card and moves across to a sibling, or back up through return.

To pause, the loop simply returns. The variable still holds the cursor, and the next slice of time carries on from the same card. Time slicing, interrupting a render for something more urgent and abandoning a render altogether all follow from this one representation. Dive 05 covers the loop itself.

The ideaworkInProgress is the whole “where am I”

From the source
performUnitOfWork, with the profiler and DEV branches folded into one callReactFiberWorkLoop.js:3067–3109 ↗
function performUnitOfWork(unitOfWork) {
  const current = unitOfWork.alternate;          // the on-screen version
  const next = beginWork(current, unitOfWork, entangledRenderLanes);
  unitOfWork.memoizedProps = unitOfWork.pendingProps;
  if (next === null) {
    completeUnitOfWork(unitOfWork);   // no children: finish, then go across or up
  } else {
    workInProgress = next;            // ← the entire "where am I" state
  }
}
RootAppHeaderskippedListFooterskippedRow AskippedRow BchildLaneschildLaneschildLanessetState · lanes

React 04 · 5 of 14

Little flags raised up the chain

Every card carries two notes about waiting work. lanes means “work is scheduled on me”. childLanes means “work is scheduled somewhere below me”.

When you call setState in a row deep in the tree, React marks that row’s lanes, then walks the return strings up to the root, raising a little flag on each ancestor: it ORs the lane into each one’s childLanes. The function that does it is markUpdateLaneFromFiberToRoot.

The next render follows only the raised flags. A card whose lanes and childLanes are both empty has nothing to do here or below, so the whole drawer under it is skipped. In a page of a thousand components, an update in one row touches the path to that row and nothing else.

Keep the shape of this idea in mind, a summary on the parent so the parent never has to ask its children. It is the most reused idea in the reconciler, and it comes back for commit at the end of this dive.

The ideachildLanes lets render skip whole subtrees

From the source
Raising the flags: the walk up to the root, abridgedReactFiberConcurrentUpdates.js:189–210 ↗
function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
  sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
  …
  let parent = sourceFiber.return;
  while (parent !== null) {
    parent.childLanes = mergeLanes(parent.childLanes, lane);
    …
  }
}
0fn1class23root45host6text78910111213susp14151617181920212223242526272829throw3031newest2 and 20: retired, never reusedReactWorkTags.js · 30 tags

React 04 · 6 of 14

Thirty kinds of card

A card’s tag is a small number saying what kind of position it is, and every switch in the reconciler keys on it. ReactWorkTags.js is 73 lines of these constants, thirty of them.

The common ones: 0 is FunctionComponent, whose hooks live in memoizedState. 1 is ClassComponent, whose stateNode is the instance. 3 is HostRoot. 5 and 6 are HostComponent and HostText, a <div> and a text node, whose stateNode is the real DOM node. 13 is SuspenseComponent, where a thrown promise is caught. The newest is 31, ActivityComponent.

The tag is assigned when the card is made, by createFiberFromTypeAndProps, from the four kinds of type Dive 03 listed. A function is a FunctionComponent, unless its prototype has isReactComponent, a marker on React.Component, in which case it is a class. A string is a host component. Symbols like the fragment get their own cards. Wrapper objects are sorted by their own $$typeof: context, forwardRef, memo, lazy.

The numbers run 0, 1, 3–19 and 21–31. 2 and 20 were IndeterminateComponent and FundamentalComponent, both removed, and their numbers were never reused. DevTools keeps its own table of these numbers for each React version, which is one good reason to leave a retired number alone.

The ideaThe tag picks the branch; the type decides the tag

From the source
Some of the thirty tags
TagNameWhat it is
0FunctionComponentThe common case. Hooks live in memoizedState.
1ClassComponentstateNode is the instance.
3HostRootThe root; stateNode is the FiberRoot.
5 / 6HostComponent / HostTextA <div> and a text node. stateNode is the real DOM node.
7FragmentA position with children and no host output.
9 / 10ContextConsumer / ContextProviderDifferent work, so different tags.
13SuspenseComponentWhere a thrown promise is caught.
14 / 15MemoComponent / SimpleMemoComponent“Simple” is the fast path: a plain function, no custom compare, no defaultProps.
16LazyComponenttype stays null until it resolves.
22OffscreenComponentThe hidden-but-alive subtree under Activity and Suspense.
26 / 27HostHoistable / HostSingleton<link> and <meta> hoisted to <head>; <html> and <body>, which exist once.
29ThrowA card whose only job is to raise an error (next scene).
31ActivityComponentThe newest tag.
How a tag is chosen, abridged: createFiberFromTypeAndPropsReactFiber.js:554–737 ↗
let fiberTag = FunctionComponent;
let resolvedType = type;
if (typeof resolvedType === 'function') {
  if (shouldConstruct(resolvedType)) fiberTag = ClassComponent;  // prototype.isReactComponent
} else if (typeof resolvedType === 'string') {
  fiberTag = isHostHoistableType(type, pendingProps, hostContext) ? HostHoistable
           : isHostSingletonType(type)                            ? HostSingleton
           : HostComponent;
} else {
  getTag: switch (resolvedType) {
    case REACT_FRAGMENT_TYPE: return createFiberFromFragment(…);
    // …activity
    default: {
      switch (resolvedType.$$typeof) {          // ← the wrapper objects
        case REACT_CONTEXT_TYPE:     fiberTag = ContextProvider; break getTag;
        case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef;      break getTag;
        case REACT_MEMO_TYPE:        fiberTag = MemoComponent;   break getTag;
        case REACT_LAZY_TYPE:        fiberTag = LazyComponent; resolvedType = null; break getTag;
      }
      // …nothing matched: the type is invalid (next scene)
    }
  }
}
const fiber = createFiber(fiberTag, pendingProps, key, mode);
fiber.elementType = type;          // ← what was written
fiber.type = resolvedType;         // ← what to actually call
elementtype: undefined(mixed-up import)tag 29 · ThrowpendingProps:new Error('Element type is invalid…')boundary

React 04 · 7 of 14

A bad slip becomes a card that throws

You have probably seen “Element type is invalid… but got: undefined”. It usually means a mixed-up default and named import: the slip’s type is undefined, which matches none of the four kinds.

React does not throw at that moment. It makes a card anyway, with tag 29, Throw, and puts a new Error in its pendingProps. The error is the props. When the work loop reaches that card, its only job is to raise it.

The source comment gives the reason. A bad type is conceptually a child that failed, not the component that rendered it. Making it a child card gives the error the slip’s owner and stack, so it points at your JSX line, and it travels through the normal error-boundary path like any other render error.

The pattern is worth stealing: when you detect a failure at a place with good context but bad timing, turn it into a value and report it where the timing is right.

The ideaThe error is stored as data and raised in its turn

From the source
The fallback at the end of createFiberFromTypeAndPropsReactFiber.js:711–722 ↗
// The type is invalid but it's conceptually a child that errored and not the
// current component itself so we create a virtual child that throws in its
// begin phase. This is the same thing we do in ReactChildFiber if we throw
// but we do it here so that we can assign the debug owner and stack from the
// element itself. That way the error stack will point to the JSX callsite.
fiberTag = Throw;
pendingProps = new Error(
  'Element type is invalid: expected a string (for built-in ' +
    'components) or a class/function (for composite components) ' +
    `but got: ${typeString}.${info}`,
);
resolvedType = null;
FiberRootroot.currentcurrent · on screenwork-in-progressHostRootHostRootalternateAppAppalternate<li><li>alternateDOM <li>

React 04 · 8 of 14

Every card has a carbon twin

React keeps at most two versions of the tree. The source calls it “a double buffering pooling technique”. The current tree is the one on screen. The work-in-progress tree is the one being built for the next render. Each card’s alternate points at its twin in the other pile.

Render builds the work-in-progress pile and never writes on the current one. So if something more urgent arrives in the middle, a keystroke say, React can drop the half-built pile, and the screen is still consistent: nothing it shows was touched.

Both twins point at the same stateNode. React double-buffers its own bookkeeping, not the DOM: there is one real <li> node, and both versions of its card refer to it.

The twin is made lazily, the first time a position updates, and from then on no new card is allocated for that position. The two objects just trade roles on every commit, forever.

The ideaBuild the next tree beside the visible one

Check yourselfDuring a render, the card being worked on has alternate === null. What does that tell you?
From the source
Where the twin is made: the first branch of createWorkInProgress, DEV fields left outReactFiber.js:323–351 ↗
export function createWorkInProgress(current, pendingProps) {
  let workInProgress = current.alternate;
  if (workInProgress === null) {
    // We use a double buffering pooling technique because we know that we'll
    // only ever need at most two versions of a tree. We pool the "other" unused
    // node that we're free to reuse. This is lazily created to avoid allocating
    // extra objects for things that are never updated. …
    workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
    workInProgress.elementType = current.elementType;
    workInProgress.type = current.type;
    workInProgress.stateNode = current.stateNode;   // ← the SAME DOM node
    workInProgress.alternate = current;
    current.alternate = workInProgress;
  } else { … }
FiberRootold treefinishedWorkcurrentmutationlayoutcomponentWillUnmountcomponentDidMountroot.current = finishedWork

React 04 · 9 of 14

One assignment swaps the piles

When the work-in-progress pile is finished and its changes are applied, the office does not copy anything back. It moves one pointer. The root object keeps a field called current, the pile on display, and commit sets it to the finished pile: root.current = finishedWork.

After that line, the two trees have swapped roles. The pile that was being built is now the one on screen, and the old one becomes the scratch pile for the next update, with every card’s alternate already pointing the right way.

Where the line sits matters. It runs after the mutation phase, where the DOM is changed, and before the layout phase. So componentWillUnmount, which runs during mutation, still sees the old tree, while componentDidMount and layout effects see the new one. Dive 10 walks through those phases.

The ideaCommit flips one pointer: root.current

From the source
The swap, with the comment that explains its placeReactFiberWorkLoop.js:4033–4037 ↗
// The work-in-progress tree is now the current tree. This must come after
// the mutation phase, so that the previous tree is still current during
// componentWillUnmount, but before the layout phase, so that the finished
// work is current during componentDidMount/Update.
root.current = finishedWork;
currentwork-in-progressmemoizedStatememoizedStatecopiedmemoizedPropsmemoizedPropscopiedchildchildcopieddependenciesdependenciesnewclonedflagsflags0cleareddeletionsdeletions0clearedstateNodestateNodesharedcreateWorkInProgress

React 04 · 10 of 14

What the twin copies, clones and clears

Each time a twin is reused, createWorkInProgress fills it in from the card on screen, and every field gets one of three treatments.

Copied: child, memoizedProps, memoizedState and updateQueue are carried straight over. That is how your useState value survives: the hooks list on the screen card becomes the starting point of the new one.

Cleared: flags, subtreeFlags and deletions are reset, because they are a verdict about one render (“insert me”, “update me”), and last time’s verdict must not repeat. Only the static bits of flags are kept, which the next scene explains.

Cloned: dependencies, the list of contexts the card reads, gets a fresh object. The source says it is mutated during render. If both twins shared it, a render that was later abandoned would leave its marks on the tree that is still on screen.

This also explains what “changing a key resets state” means. With a new key, the new slip is no longer paired with the old card. A new card is made with memoizedState: null, and the old one goes into the parent’s deletions. That is all there is to it.

The ideaCopy what lasts, clear what was one render’s verdict

Check yourselfWhy must dependencies be cloned rather than shared with the on-screen card?
From the source
The rest of createWorkInProgress, abridgedReactFiber.js:352–436 ↗
  } else {
    // EVERY later update: reuse the twin, clear last time's verdict
    workInProgress.pendingProps = pendingProps;
    workInProgress.flags = NoFlags;
    workInProgress.subtreeFlags = NoFlags;
    workInProgress.deletions = null;
  }

  // Reset all effects except static ones.
  // Static effects are not specific to a render.
  workInProgress.flags = current.flags & StaticMask;
  workInProgress.childLanes = current.childLanes;
  workInProgress.lanes = current.lanes;

  workInProgress.child = current.child;
  workInProgress.memoizedProps = current.memoizedProps;
  workInProgress.memoizedState = current.memoizedState;   // ← your hooks, carried over
  workInProgress.updateQueue = current.updateQueue;

  // Clone the dependencies object. This is mutated during the render phase, so
  // it cannot be shared with the current fiber.
  workInProgress.dependencies = … { lanes, firstContext } …;
  …
  return workInProgress;
}
One position over three rendersOur example, not from the source
// <Row key="a" id={3} />, rendered and then updated to id={4}

// render 1: a new card
typeof Row === 'function', no prototype.isReactComponent  ⇒  tag 0
fiber = {tag: 0, key: "a", elementType: Row, type: Row,
         pendingProps: {id: 3}, memoizedState: null, alternate: null}

// render 2: same position, same key, same elementType
createWorkInProgress(current, {id: 4})
  → alternate === null, so allocate the twin ONCE
  → wip.memoizedState = current.memoizedState     // useState survives
  → wip.pendingProps  = {id: 4}

// render 3: no allocation; wip and current trade places
flags0b…signbit 30: the last free one, now takenPassiveCallback = HydrateUpdatePlacement31 bits · all used · some shared

React 04 · 11 of 14

Thirty-one holes, all punched

What commit must do at each card is recorded as bits in one number, flags, like holes punched along the card’s edge. ReactFiberFlags.js writes every bit out in full binary: Placement (insert or move), Update, ChildDeletion, Ref, Passive (a useEffect to run), and many more.

Why 31 and not 32? JavaScript’s bitwise operators work on signed 32-bit integers, and the sign bit is left alone. All 31 positions are now taken. The file’s own comment had warned “we’re about to run out of bits”.

So bits are shared. Hydrate is the same bit as Callback, FormReset the same as Snapshot, ScheduleRetry the same as StoreConsistency, and there are others. One hole means different things on different kinds of card. That is safe only while the two meanings never apply to the same tag, and only a comment records that rule.

Some bits are different in kind. A static bit like PassiveStatic records a fact about the component: it contains a useEffect. Those are the bits createWorkInProgress keeps when it clears the rest.

The ideaEffect bits are one render’s verdict; static bits are facts

Check yourselfWhen a twin is reused, why are its flags reset but the StaticMask bits kept?
From the source
Some of the bits, and the shared onesReactFiberFlags.js:18–51 ↗
export const NoFlags       = 0b0000000000000000000000000000000;
export const PerformedWork = 0b0000000000000000000000000000001;
export const Placement     = 0b0000000000000000000000000000010;
export const Update        = 0b0000000000000000000000000000100;
export const ChildDeletion = 0b0000000000000000000000000010000;
export const Ref           = 0b0000000000000000000001000000000;
export const Snapshot      = 0b0000000000000000000010000000000;
export const Passive       = 0b0000000000000000000100000000000;
export const Visibility    = 0b0000000000000000010000000000000;
…
// It's OK to reuse these bits because these flags are mutually exclusive for
// different fiber types. We should really be doing this for as many flags as
// possible, because we're about to run out of bits.
export const Hydrate = Callback;
export const ScheduleRetry = StoreConsistency;
export const ShouldSuspendCommit = Visibility;
export const DidDefer = ContentReset;
export const FormReset = Snapshot;
The bits that survive a cloneReactFiberFlags.js:138–150 ↗
// Union of tags that don't get reset on clones.
// This allows certain concepts to persist without recalculating them,
// e.g. whether a subtree contains passive effects or portals.
export const StaticMask =
  LayoutStatic |
  PassiveStatic |
  RefStatic |
  MaySuspendCommit |
  ViewTransitionStatic |
  ViewTransitionStaticParent |
  ViewTransitionNamedStatic |
  PortalStatic |
  Forked;
RootAppHeadernot visitedListFooternot visitedRow Anot visitedRow BUpdatesubtreeFlags set belowsubtreeFlags & MutationMask === 0 → skip

React 04 · 12 of 14

Skipping whole drawers at commit

Commit has the same problem render had: it should not visit a thousand cards to apply three changes. The answer is the same shape as childLanes. subtreeFlags is the OR of every flag below a card, a summary on the parent.

It is built on the way up. As each card completes, bubbleProperties in ReactFiberCompleteWork.js ORs every child’s flags and subtreeFlags into the parent, and merges the children’s lanes into childLanes the same way.

Each part of commit then checks a mask before going down. If subtreeFlags & MutationMask is zero, no card in that drawer is visited. The cost of commit follows the number of changed cards, not the size of the tree.

Older material describes a linked “effect list” (firstEffect, nextEffect). Those fields are gone from the fiber. Commit is now a tree walk that prunes, not a list to iterate. In one line: render skips on childLanes; commit skips on subtreeFlags.

The ideaRender skips on childLanes; commit skips on subtreeFlags

From the source
The masks each commit phase checks before descendingReactFiberFlags.js:120–132 ↗
export const MutationMask =
  Placement |
  Update |
  ChildDeletion |
  ContentReset |
  Ref |
  Hydrating |
  Visibility |
  FormReset;
export const LayoutMask = Update | Callback | Ref | Visibility;

// TODO: Split into PassiveMountMask and PassiveUnmountMask
export const PassiveMask = Passive | Visibility | ChildDeletion;
1ReactInternalTypes.js2ReactWorkTags.js3ReactFiber.js · FiberNode4ReactFiber.js · createWorkInProgress5ReactFiber.js · createFiberFromTypeAndProps6ReactFiberFlags.js7ReactFiberWorkLoop.jsreact-reconciler/src

React 04 · 13 of 14

How to read the planning office

These files are where everything in this dive is written down. In this order, each one makes the next easier:

  1. ReactInternalTypes.js, the Fiber type: read the comments on every field.
  2. ReactWorkTags.js, all 73 lines: the vocabulary, and the missing 2 and 20.
  3. ReactFiber.js lines 134–221: FiberNode and the five-point comment after it.
  4. ReactFiber.js lines 323–437: createWorkInProgress. For each field, ask: copied, cloned or reset?
  5. ReactFiber.js lines 554–765: createFiberFromTypeAndProps, ending at the Throw fallback.
  6. ReactFiberFlags.js, all 150 lines: the bit layout, the shared bits and the commit masks.
  7. ReactFiberWorkLoop.js: performUnitOfWork, and the one-line swap at line 4037.

The ideaRead the type first, then who makes it

From the source
An exercise: walk the cards by handOur example, not from the source
// In React DevTools, select a component; in the console it is $r.
// From there, follow the strings yourself:
$r.return, $r.child, $r.sibling, $r.alternate

// "Why did this render?" tools compare these two:
$r.memoizedProps
$r.alternate.memoizedProps
react-reconcilerfibertagstateNodememoizedStatealternate

React 04 · 14 of 14

What to keep

  • The fiber holds what the element cannot: state, the host node, pending work, and its position in the tree.
  • It is a struct: no methods, no instanceof, fixed fields.
  • child, sibling and return replace the call stack with data, so the whole traversal position is one variable and rendering can pause.
  • tag picks one of 30 kinds of node, assigned by structural checks. An invalid type becomes a Throw fiber, not an immediate exception.
  • alternate is double buffering: two fibers per position, reused forever; the visible tree is never written during render.
  • The swap is root.current = finishedWork, between mutation and layout.
  • childLanes and subtreeFlags are summaries on the parent that let render and commit skip untouched subtrees.
  • The 31-bit flags field is full, so some bits are shared between fiber types that never overlap.

Read from facebook/react at dcd4ec28a1 (react 19.3.0, 26 July 2026). Line numbers are from that commit.

Back to all chapters ↑