Read “Build your own React”
Recently I went through the Build your own React post, this is a great post on how React works basically, which I would suggest all front end developers should check out although the post was 3 yrs old( ❗❗️️️ should refer to the latest React blog for the up-to-date concepts, APIs, terms etc.)
There are 9sections
0. What do React.createElement, under the JSX hood, and ReactDOM.render do basically?
This section is really friendly for beginners. The author uses some lines of code to explain 1. React.createElement is creating a javascript object as a react element, 2. ReactDOM.render is mounting the html node of the element to the DOM root node
- Introduce Babel to transpile JSX by using own createElement* function
- First version of render function
The function recursively creates HTML elements from corresponding element and append it to parent until the whole tree is mounted - Concurrent mode (Concurrency) in React
No matter what is the name of the mechanism, the core of it is the render process can be interrupted, and guarantee the users’ interaction still to be responsive, which means the render process will not block the main thread.
The implementation in this post isreqestIdleCallback
which shares the same idea with React’s implementation conceptually. - Fibers in React
Fibers, often so called v-dom, manage the whole React app by building a tree structure in React.
Each React element has its own fiber. From the root fiber each fiber has three pointers pointing to the element’s parent, direct child and direct sibling respectively ,which make traversing the whole tree possible, and this the key for React on each update - Separate Render and commit phases
Fiber tree update is very fast because it’s all about pure javascript object manipulating, whereas DOM changes are often time consuming because using web API to manipulate DOM very often gets reflow and repaint involved which always take up time on the main thread.
So a good way to reduce frequent DOM manipulations is to gather all the changes and apply them in one run, having a separate fiber tree update phase and committing in another phase can help with that. In addition, applying changes to the DOM should be done in a single task, then users will not see partial UI updates. - Reconciliation
Creating a new fiber with a pointer pointing to the old fiber and linking all new fibers as the new fiber tree whenever there is an update is basically how React updates. - Function component
Unlike native HTML tag element, a function component element doesn’t have a corresponding DOM node, all children of function component fiber are from running the function. - Hooks
Each fiber will host all its corresponding function component hooks in an array. And on each update, all hooks will run sequentially to get the latest corresponding value, that’s why the order of hooks should be maintained on each re-render.