What is the reconciler?
- React course
- Expert
- Lesson 17/32
- 4 min
Learn that the reconciler performs diffing.
What is the reconciler?
The reconciler is the part of React that compares the old and new component trees and computes the changes. ReactDOM.render writes output to the screen; the reconciler tells what changed.
The old tree is called current and the new tree work-in-progress. The two trees are compared and differences are added to a side-effect list.
This comparison is called diffing and runs in O(n) complexity; the tree is scanned level by level, not fully.
The diffing algorithm
Diffing makes three assumptions when comparing two trees: elements of different types produce different trees, elements of the same type keep their position, and list items are matched by key.
Thanks to these assumptions the tree is scanned in O(n). Without them all possibilities would take O(n³).
Without a key React matches list items by position; this causes unnecessary DOM updates.
Practice Write the reconcile function
Write a reconcile function. Take oldNode and newNode parameters. If oldNode.type !== newNode.type return { action: 'replace', node: newNode }. If oldNode.props !== newNode.props return { action: 'update', node: newNode }. Finally return { action: 'skip' }. Export it.
Starter code
// Write the reconcile function hereSample solution
function reconcile(oldNode, newNode) {
if (oldNode.type !== newNode.type) {
return { action: 'replace', node: newNode };
}
if (oldNode.props !== newNode.props) {
return { action: 'update', node: newNode };
}
return { action: 'skip' };
}
export default reconcile;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the reconciler do?
- Applies CSS styles
- Compares two trees and computes differences Correct answer
- Sends HTTP requests
- Generates TypeScript types
Explanation: The reconciler finds changes via diffing.
2 Fill in the blank: add a key to a list item
{items.map(item => <li ____={item.id}>{item.name}</li>)}
{items.map(item => <li key={item.id}>{item.name}</li>)}
Explanation: key matches list items correctly.
3 Match reconciler concepts
| Term | Meaning |
|---|---|
current |
Old tree |
work-in-progress |
New tree |
diffing |
Comparison |
key |
List matching |