What is React?

A javascript library for building the interface

Features:

  • declarative
  • Component type

Advantages:

  • The development team and community are strong
  • The API is simple

Disadvantages:

  • There is no official system solution, and the selection cost is high
  • Too flexible and demanding in code design

JSX is the syntactic sugar for React. CreateElement

React class components and function components

Same: both can accept props and return the React object

Different:

  • Programming philosophy and memory: Class components need to create instances object-oriented programming, it will save instances, need a certain amount of memory overhead, while functional components oriented programming, memory can be saved

  • Testability: The functional approach makes more use of writing unit tests

  • Capture feature: Function components have value capture feature (can only get values before rendering)

  • State: The class component defines the state, and the function uses useState

  • Life cycle: Class components have a full life cycle while components do not, and you can use useEffect to implement the class life cycle functionality

  • Logical reuse: Class components are used for logical reuse through inheritance or higher-order components, and function components are used for reuse through custom components

  • Skip updates: Class components can skip updates with shouldComponents and PureComponents(shallow comparisons, deep comparisons can use immer), function components react. Memo skips updates

  • Prospects: Function components will become mainstream because they better mask this problem, and reuse logic, better suited to time sharding and concurrent rendering

React Design Concept

  • Cross-platform rendering => virtual DOM
  • Fast response => Asynchronous interruptible (Fiber)+ incremental update

fiber

Fiber is an execution unit. After each execution, React detects how much time is left in the current frame, and if there is no time left, the controller will be sent out

Fiber is a data structure

  • React’s current approach uses linked lists, with each VDOM node represented internally as a fider

  • You start with the vertices

  • If there is a first son, the first son is traversed first

  • If there is no first son, the node is traversed

  • If there is a younger brother, traverse the younger brother

  • If there is no younger brother, the parent node is returned to mark the completion of the parent node traversal, if there is an uncle traversal uncle

  • The traversal ends without an uncle

(Son = > brother = > uncle)

Fiber appears background

The Act15 architecture does not support asynchronous updates, and stuck frames occur when rendering a large number of components recursively for more than 16.7ms

The Act16 architecture can be divided into three layers:

  • Scheduler (a Scheduler similar to the requestIdleCallback function) — Schedules the priority of tasks, and high-priority tasks are given priority to enter Reconciler

  • Reconciler — the components that identify change

  • Renderer – Responsible for rendering the changing components onto the page

React rendering is a three-step process

  • scheduling

  • harmonic

  • Submission (not suspended)

Fiber realizes key principles

  • Based on requestIdleCallback, get the current frame with time remaining deedLine (queued functions that will be called during the browser’s idle time)
  • Since compatibility is actually using Messagechannel + requestAnimationFrame to emulate requestIdleCallback

A dom element will be operated on. The chain of side effects is the descendant of the dom element. The effect is inverted fiber to build a DOM node

The effect of fiber

  • Ability to slice interruptible tasks.

  • The ability to interleave parent and child elements to support layout in React.

  • Ability to return multiple elements in render().

  • Better support for error boundaries.

The principle uses the requestIdleCallback function to queue functions that are called during the browser’s idle time. This enables developers to perform line background and low-priority work on the main event loop without affecting the delay of critical events, such as animation and input responses.

Fiber recursive process

Function performUnitOfWork(fiber) {beginWork if (fiber.child) {performUnitOfWork(fiber.child); } // Execute completeWork if (fibre.sibling) {performUnitOfWork(fibre.sibling); }}Copy the code

React vs. Vue

The same:

  • Both front-end interfaces implement javascript libraries

  • Both can implement data-driven template updates without directly manipulating dom, and the core is VDOM

Different:

  • Vue uses data hijacking to update the interface automatically when data changes, while React calls setState.

  • The granularity of Vue updates is the current component, while React includes sub-components in addition to the current component (performance bottlenecks).

  • In terms of design, Vue data is separated from templates and methods, while React does not. Vue has a lot of instructions, while React only has JS

  • In diff, when a Vue className is inconsistent, it considers different nodes, while React considers the same node. Vue has heads, tails, and cross-comparisons, while React does not.

  • Asynchronous slice updates can be implemented in versions after React16 with Fider

  • React doesn’t have an existing family bucket stack like Vue, so you need to choose and measure it yourself, which requires time to step on the pit. Besides, the use of React periphery is not very simple and clear, so you need to understand the writing method and best practices of the selected periphery, which takes time and increases the threshold to get started

  • React has a better ecosystem than Vue

hook

Hooks are functions that allow you to “Hook” React state and lifecycle features into function components, allowing you to use state in function components.

SetState is asynchronous or synchronous

React’s setState is not asynchronous per se because its batch processing mechanism gives the illusion of asynchrony.

React update mechanism

Life cycle functions and composition events:

  1. No matter how many times setState is called, the update will not be performed immediately. Instead, the state to be updated is stored ‘_pendingStateQuene’ and the component to be updated is stored ‘dirtyComponent’;
  2. When the root component didMount, the batch mechanism is updated to false. Fetch state and component from ‘_pendingStateQuene’ and ‘dirtyComponent’ for merge update;

In native events and asynchronous code:

  1. Native events (native JS bound events) do not trigger the React batching mechanism, so calling setState will update directly;
  2. SetState is called in asynchronous code. Due to the asynchronous processing mechanism of JS, asynchronous code will be temporarily stored and wait for the synchronous code to complete execution. At this time, the react batch processing mechanism has ended, so it will be updated directly.

Summary: React behaves both synchronously and asynchronously (setTimeout/setInterval), but is essentially synchronous. Its batch processing mechanism creates the illusion of asynchracy. (It is perfectly possible to treat this as asynchronous during development, in composite events and lifecycle functions)

React synthesis event

16 Event flow (no separate capture and bubbling event bugs registered)

Bug: Popover doesn’t work when clicked

Cause: The click event bubbles directly into the Document native event, and the state changes to false

Solution:

Principle:

17 event flow

The event delegate is no longer a Document but a mount point container, allowing multiple React versions to be used on a single page

Instead of mounting to document, nodes become parent-child relationships so stopPropagation works

redux

When to use Redux:

  • The state of a component that needs to be shared
  • A state needs to be available anywhere
  • A component needs to change global state
  • One component needs to change the state of another component