(Add star to front end to improve front end skills)

Author: Front-end Jiajia Public number/Guangzhou PeEN (this article is submitted by the author)

Here are all the common react interview questions, with detailed answers. If you want to learn more about the underlying principles, check out the suggested reading at the end of this article.

Question list

  • Comparison and use of HOC, Render props, and hooks.
  • What is the virtual DOM?
  • React Diff principle, how to go from O(n^3) to O(n)
    • Why use key? What are the benefits?
  • The principle of JSX
    • Why must the React component be capitalized
  • When is setState synchronous and when is it asynchronous?
  • How does React implement its event mechanism?
    • What is the difference between React events and native events
  • Talk about fiber architecture
  • Why bind this to the React event or use the arrow function? What’s the difference

If you know all of the above, then you can close this page.

HOC, render props, and hooks

For more details, see another post: Interviewer: Talk about HOC, Render props, Hooks

What is the virtual DOM?

React converts the code into a JS object, and then converts the JS object into the actual DOM. This JS object is called the virtual DOM.

It lets us forget about DOM manipulation and just have fun writing data, state.

React Diff principle, how to change from O(n^3) to O(n)

  • Why order n^3?

The intuitive way to go from one tree to another is to use dynamic programming, which reduces time complexity through this mnemonic search. Since a tree is a recursive data structure, the simplest tree comparison algorithm is recursive processing. To be precise, the time complexity of the tree minimal distance editing algorithm is O(n^2m(1+logmn)), and we assume that m is of the same order as n, which becomes O(n^3).

Recommended reading (why O(n^3))[1]:

  • The react principle of the diff

Simply put, React only compares the same layer and deletes it when it differs. So each node is only compared once, so the algorithm becomes O(n).

For a group of child nodes of the same layer. React distinguishes components based on key values. If the key values are the same, the components are returned without re-creation.

This is why there are some weird bugs when rendering arrays without adding keyvalues or having duplicate keys.

In addition to keys, selection subtree rendering is also provided. Developers can rewrite shouldComponentUpdate to improve diff performance.

Recommended reading (Diff’s Principle)[2]

Principle of JSX

<div>Hello ConardLi</div>Copy the code

In fact, Babel helped us translate this syntax into

React.createElement('div', null, `Hello ConardLi`)Copy the code
Why custom components must be capitalized.

Babel determines the initial letter of the JSX component during compilation. If it is lowercase, it is a native DOM tag and is compiled as a string. If it is uppercase, it is considered a custom component. Compile to an object.

Why does the following code report an error?
return (<a></a><a></a>)Copy the code

Again, because we create the component as react.createElement (), there can only be one root node. If you want to use two parallel nodes, wrap them with <></>. <></> will be compiled to < react. Fragment/>.

Babel translates it as follows:

Play the conversion yourself, deepen the impression of it

Babel transformation [3]

When is setState synchronous and when is it asynchronous?

By “asynchronous” I do not mean asynchronous code implementation. React collects changes and then updates them uniformly.

SetState is synchronized in both native events and setTimeout. Asynchronous in composite events and hook functions.

In setState, an isBatchingUpdates is used to determine whether to update directly or later, which defaults to false. However, React will call the batchedUpdates function before calling the event handler. The batchedUpdates function will set isBatchingUpdates to true. Thus, event processing controlled by React becomes asynchronous (batch updates).

React: The event mechanism

Let’s start with a classic image of bubble capture:

In the component mount phase, according to the component life’s React event, add the document event addEventListener, and add the unified event handler dispatchEvent.

Associate all events with event types and the React component and store the relationship in a map. When the event is triggered, the synthesis event is generated first, the corresponding event function is found according to the component ID and event type, the capture process is simulated, and then the corresponding function is triggered successively.

If bubbling is prevented by native events using stopPropagation, then composite events are also prevented.

How is the React event mechanism different from native events
  1. React events are named with a hump, as opposed to the original all lowercase name.
  2. It is not possible to prevent the default behavior by returning false, it must explicitly call preventDefault to prevent the browser’s default response.

React event system and source code [4]

What is React Fiber

Background: Thanks to the browser it brings together GUI rendering, timer handling, event handling, JS execution, and remote resource loading. If you perform a JS update, a process that takes too long can cause the browser animation to fail or the input response to be slow.

React Fiber uses two core solutions:

  • Prioritize rendering
  • interruptible

React Fiber divides the virtual DOM update process into two phases, the Reconciler reconciliation phase and the COMMIT phase. See below:An update process is divided into many pieces, so it is possible that a task can be interrupted by a higher priority update process before it is completed, at which point the lower priority work is completely abandoned and waiting for the opportunity to come back.

Scheduling process

requestIdleCallback

RequestIdleCallback expriationTime. requestIdleCallback expriationTime. requestIdleCallback expriationTime. requestIdleCallback expriationTime. requestIdleCallback Call channel.port1.onMessage to determine whether the current time is less than the time of the next frame. If the time is less than the time of the next frame, it means that we have free time to execute the task. If the time is greater than the time of the expired task, if the task is not expired. The task is dropped to the next frame.

React implements a requestIdleCallback itself due to compatibility issues with the requestIdleCallback

React Fiber Architecture [5]

Why bind this or use arrow function in React event?

Actually, it’s not really a react problem, it’s a this problem. React is a common problem. So let’s talk about that

<button type="button" onClick={this.handleClick}>Click Me</button>Copy the code

When the event is raised and called, because this is bound at run time, his falls back to the default binding, which is undefined, because the class declaration and stereotype methods are run in strict mode.

We can bind to component instances using bind. You don’t have to worry about its context.

Because this in the arrow function refers to this at definition, not this at execution. So the arrow function can be solved as well.

How to optimize your Super-large React application

React history: Virtual DOM and its value

Move the universe! React can also “use” computed properties

Find this article helpful? Please share it with more people

Pay attention to “front-end daqo” plus star label, improve front-end skills

Good article, I’m reading ❤️