Summary - React internals
- React course
- Expert
- Lesson 20/32
- 5 min
Build a fiber node by hand and explain the diff logic with an example.
Summary - React internals
In this group you learned the reconciler, the fiber tree and the commit phase.
The reconciler compares two trees via diffing; fiber nodes are traversed like a linked list and rendering can be paused; the commit phase writes to the DOM synchronously.
Now you will write a diff function.
Practice Write the diffNodes function
Write a diffNodes function. Take oldNode and newNode parameters. If !oldNode return { action: 'add', node: newNode }. If !newNode return { action: 'remove' }. If oldNode.type !== newNode.type return { action: 'replace', node: newNode }. Finally return { action: 'update', node: newNode }. Export it.
Starter code
// Write the diffNodes function hereSample solution
function diffNodes(oldNode, newNode) {
if (!oldNode) return { action: 'add', node: newNode };
if (!newNode) return { action: 'remove' };
if (oldNode.type !== newNode.type) return { action: 'replace', node: newNode };
return { action: 'update', node: newNode };
}
export default diffNodes;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is wrong?
- Commit can be interrupted Correct answer
- Fibers are traversed via child and sibling
- key does list matching
- The reconciler does diffing
Explanation: Commit is synchronous and atomic; it cannot be interrupted.
2 Fill in the blank: move to the sibling fiber
if (fiber.child) commitWork(fiber.child);
if (fiber.____) commitWork(fiber.sibling);
if (fiber.child) commitWork(fiber.child);
if (fiber.sibling) commitWork(fiber.sibling);
Explanation: sibling processes the sibling fiber.
3 Match concepts
| Term | Meaning |
|---|---|
reconciler |
Compares two trees |
fiber |
Internal data structure |
commit |
Writes to DOM |
diffing |
Finds differences |