See react source code has a period of time, write an article summary, also hope to help you. This is the first article in the React Principles series. It mainly explains the basic structure of react, so that you can have an overall understanding.

  1. What is thefiber, why use itfiber
  2. reactThe three-tier architecture model of:scheduler - reconciler - renderer
  3. reactSynthetic events are triggered when we click a buttonclickWhat happened during the event
  4. reactHow is the update triggered (class componentsetState, function componentuseState)
  5. reactThe updatedrenderphase
  6. reactThe updatedcommitphase
  7. schedulerThe process of scheduling tasks

The React version of the articles is 17.0.2

What is the fiber

Each fiber is an object. Each component (such as an App component), and each real DOM node corresponds to a fiber object. The fiber object has many properties.

Fiber: {
  return: Fiber | null.child: Fiber | null.sibling: Fiber | null.stateNode: null
}
Copy the code

The Return attribute points to the parent fiber, the Child attribute points to the first child fiber, the Sibling executes its next sibling fiber node, and the stateNode executes the corresponding component of the fiber object or the real DOM node.

Why use fiber

Before adopting the Fiber architecture, React processed the virtual DOM recursively, causing react to occupy the main thread for too long and possibly causing page feign death. As you can see from the previous figure, the Fiber tree is a multi-tree similar to a linked list structure. Each fiber is an independent unit of work, which facilitates interruptible updates. Consider the following two cases:

  1. reactDuring the update, the user clicks the button
  2. Page animation

For case 1, React wants the user to respond as quickly as possible when a click event is triggered, so the page animation doesn’t stall. With the Fiber architecture, each fiber is a separate unit. React interrupts the update of the fiber when an event is triggered and processes the user click event instead.

In case 2, React updates in fiber as a basic unit and allocates a time slice for each fiber. After each fiber is processed, react checks whether the time slice expires. If the time slice expires, React releases the thread to the browser to perform the corresponding page update.

To achieve the two effects mentioned above, React uses the Fiber architecture and introduces scheduler modules and the concept of priorities. Here’s a look at scheduler

Both of the situations mentioned above occur later in concurrent mode, and applications created using reactdom. render do not have these features, so React17 is also referred to as a transitional release.

The workflow of Fiber

React uses a dual cache mechanism to store the Fiber tree, meaning that there are two fiber trees in memory, called the Current tree and the workInProgress tree. The Current tree represents the fiber node that is currently displayed in the page. Each time an update is triggered, React creates a workInProgress tree based on the current tree and combined with the triggered update in a depth-first traversal. When the workInProgress is created, React switches the two trees to complete the app update.

In the actual implementation, react has one fiberRoot node and two rootFiber nodes. FiberRoot represents the root node of the entire application, starting at this node and moving down each time an update is triggered. FiberRoot has a current attribute that points to the Current tree. After each application update, switch the current pointer to complete the page update.

The two rootFiber nodes are the root nodes of the current tree and the workInProgress tree, and each current tree node and the corresponding workInProgress tree node have a pointer to each other: alternate property.

React is a complex process for creating workInProgress, which involves the Diff process of the Render phase, which will be explained separately later.

scheduler

Here is a brief introduction of the module Scheduler. This module provides the function of task scheduling and priority for tasks, so that high-priority tasks can interrupt low-priority tasks. This way, React will respond to user-triggered events when it updates.

React composite event

Looking at the code below, can you tell the output?

class App extends React.Component {
  componentDidMount() {
    outer.addEventListener('click'.function() {
      console.log('native event click outer')
    })
    
    inner.addEventListener('click'.function() {
      console.log('native event click inner')
    })
  }
  
  handleClickInner = () = > {
    console.log('react event click inner')
  }
  
  handleClickOuter = () = > {
    console.log('react event click outer')}render() {
    return (
    	<div className='outer' onClick={this.handleClickInner}>
      	<div className='inner' onClick={this.handleClickOuter}></div>
      </div>)}}Copy the code

React’s synthetic event mechanism is covered here, and there will be a special article about it later.

SetState is synchronous or asynchronous

Is setState synchronous or asynchronous? For example, the output of this code

/ / asynchronous
handleClick = () = > {
  this.setState({
    count: this.state.count + 1
  })
  this.setState({
    count: this.state.count + 1
  })
  this.setState({
    count: this.state.count + 1
  })
  console.log(this.state.count)
}

/ / synchronize
handleClick = () = > {
	setTimeout(() = > {
    this.setState({
      count: this.state.count + 1
    })
    this.setState({
      count: this.state.count + 1
    })
    this.setState({
      count: this.state.count + 1
    })
    console.log(this.state.count)
  })
}
Copy the code

There will also be an article about how React creates updates and how it handles them.

Principle of hooks

Hooks are an important update to React16. They allow us to use state in function components, and there will be an article on how they are implemented later.

Two major phases of react update

An update to React consists of two phases: the Render phase and the COMMIT phase

Render phase: includes updated computation, fiber tree diff algorithm, effectList processing, DOM node creation, class component life cycle and so on

Commit phase: includes life cycle of class components, scheduling useEffect, execution of setState callbacks, dom node insertion, and so on

There will also be an article on the two stages of the process.

Due to my limited level, the react source code has various contents and complex structure, and react17, as a transitional version, has a lot of code to prepare for concurrent mode, so it is difficult to read the React source code, and the author does not have a deep understanding of many contents, so I will not introduce it for now. If there is an opportunity in the future, I will write an article to introduce it.

Finally, I hope you can have a comprehensive understanding of the overall operation process of React after reading this series of articles.