Commit and render
- React course
- Expert
- Lesson 19/32
- 4 min
Learn to distinguish render and commit phases.
Commit and render
React rendering happens in two phases: render (computation) and commit (application). In the render phase the fiber tree is processed and side effects are computed; this phase can be interrupted.
In the commit phase side effects are applied to the DOM; this phase cannot be interrupted. The commitWork function walks the fiber tree and applies changes.
After commit useEffect and useLayoutEffect are called.
Commit phase details
The commit phase has three steps: DOM nodes are added/removed/updated, refs are attached, and useLayoutEffect is called.
These steps are synchronous and atomic; the user never sees an intermediate render. After commit the browser paints the screen.
useEffect is called asynchronously after paint; that is why it does not block the screen.
Practice Write the commitWork function
Write a commitWork function. Take a fiber parameter. If fiber.effectTag === 'update' set fiber.dom.textContent = fiber.props.text. Recurse with if (fiber.child) commitWork(fiber.child) and if (fiber.sibling) commitWork(fiber.sibling). Export it.
Starter code
// Write the commitWork function hereSample solution
function commitWork(fiber) {
if (fiber.effectTag === 'update') {
fiber.dom.textContent = fiber.props.text;
}
if (fiber.child) commitWork(fiber.child);
if (fiber.sibling) commitWork(fiber.sibling);
}
export default commitWork;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match phases
| Term | Meaning |
|---|---|
render |
Computation, interruptible |
commit |
Applies to DOM |
useEffect |
After commit |
useLayoutEffect |
Right after DOM paint |
2 What property does the commit phase have?
- Interruptible
- Asynchronous
- Runs only on the server
- Synchronous and atomic Correct answer
Explanation: Commit is synchronous and atomic.
3 Fill in the blank: when is the hook called
// after render and commit
____ is called
// after render and commit
useEffect is called
Explanation: useEffect is called after commit and paint.