What is a custom renderer?
- React course
- Expert
- Lesson 21/32
- 4 min
Learn that React can render to other targets (terminal, canvas).
What is a custom renderer?
A custom renderer renders React to a non-DOM target. For example a terminal, canvas or mobile native components can be a target.
The react-reconciler package provides React's core logic; you only write a host config. This config contains functions like createInstance and appendChild.
react-dom and react-native use the same reconciler; the difference is the host config.
Host config
The host config is the set of functions the reconciler calls. The most important ones: createInstance (new node), appendChild (add child), removeChild (remove child) and commitUpdate (update props).
These functions are written for the target environment. In the DOM document.createElement is used; in a terminal a node object is created.
With supportsMutation: true mutation mode is on; this allows direct updates.
Practice Write the hostConfig skeleton
Write a hostConfig. Set supportsMutation: true. Add createInstance: (type) => ({ type, children: [] }) and appendChild: (parent, child) => parent.children.push(child). Export it.
Starter code
// Write the hostConfig hereSample solution
const hostConfig = {
supportsMutation: true,
createInstance: (type) => ({ type, children: [] }),
appendChild: (parent, child) => parent.children.push(child),
};
export default hostConfig;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a custom renderer provide?
- Faster compilation
- Rendering outside the DOM Correct answer
- A smaller bundle
- TypeScript support
Explanation: A custom renderer paints to a non-DOM target.
2 Fill in the blank: enable mutation mode
const hostConfig = {
____: true,
createInstance: (type) => ({ type, children: [] }),
};
const hostConfig = {
supportsMutation: true,
createInstance: (type) => ({ type, children: [] }),
};
Explanation: true enables mutation mode.
3 Match host config functions
| Term | Meaning |
|---|---|
createInstance |
Creates a new node |
appendChild |
Adds a child |
removeChild |
Removes a child |
commitUpdate |
Updates props |