How does React work?

Diff algorithms, data driven, compositing events, component update mechanisms

The diff algorithm:

  1. It is an inevitable product of the virtual DOM. The old and new virtual DOM are compared (i.e., DIFF) to update the changes to the real DOM. In addition, DIFF is also required to perform the comparison process efficiently, thus reducing the time complexity O (n).
  2. In vue2. X, in order to reduce the granularity of watcher, there is only one watcher corresponding to each component, and only diff can be introduced to accurately find the changes.
  3. The moment diff occurs in vUE is when the component instance executes its update function, which compares the last render oldVnode with the new render newVnode. This process is called patch.
  4. Diff follow depth first overall process, namely comparative strategy, comparison between the two nodes according to whether they have child nodes or text node do different operations, compared two groups of child nodes is the key of the algorithm, the first hypothesis could be the same end node do 4 times than try, if not found the same node, and only in accordance with the general way to traverse the search, After the search, the remaining nodes can be processed according to the situation. With the help of key, the same node can be found very accurately, so the whole patch process is very efficient.

Data-driven: : this.setstate () maps the changing data first into the virtual DOM, and finally mounts it to update the page data

Composite events:

  1. React delegates events to the Document object.
  2. When an event is triggered by a real DOM element, the native event is processed first, and then bubbled into the Document object before the React event is processed.
  3. The react event binding time is the conciliation phase and is executed before the binding of the native event.
  4. Purpose and Advantages: For browser compatibility, React uses the top-level event proxy mechanism to ensure consistent bubbling. Event objects can be created and reclaimed frequently, so React introduces an event pool from which event objects are retrieved and released. (React17 abandoned)

In the React 16.x version, the React event is delegated to document

In react 17.x, react events are delegated to root

stopPropagation(); Stop bubbling up, but the rest of the listener functions for this element should still be executed, stopImmediatePropagation(); Prevents bubbling up, but the rest of the listener function for this element does not execute, component update mechanism

2. Front-end performance optimization?

Faster network communication

1. Let the server and users use CDN more closely:

  • 1) Global load balancing
  • 2) Cache system

2. Server communication layer

  • 1) Resources merge Sprite map
  • 2) Domain sharding multiple domain names (6-8 requests can be made for a domain name)

3. Data transmission layer – Cache

  1. The HTTP headers of this resource are used to determine whether it matches the strong cache. If yes, the cache resource is directly obtained from the local server without sending a request to the server.
  2. When the strong cache does not match, the client sends a request to the server, which verifies that the resource matches the negotiated cache through another request header, called HTTP revalidation. If the resource matches, the server returns the request, but does not return the resource. Instead, it tells the client to fetch it directly from the cache. When the client receives the return, it retrieves the resource from the cache.
  3. Strong and negotiated caches have in common that the server does not return the resource if the cache is hit; The difference is that the strong cache does not send requests to the server, but the negotiated cache does.
  4. When the negotiation cache also dies, the server sends the resource back to the client.
  5. When CTRL + F5 forces a page refresh, load it directly from the server, skipping strong cache and negotiated cache;
  6. When F5 refreshes a web page, it skips the strong cache but checks the negotiated cache.
  • 1) Strong cache

Cache-control :max-age cache-control: Expires (this field is the http1.0 specification and is a gmt-formatted time string in absolute time that represents the expiration date of a cached resource.) The strong cache uses its max-age value to determine the maximum lifetime of the cache resource, which is in seconds.)

  • 2) Negotiate cache

If-modified-since Determines whether the resource has been Modified between requests by comparing the two times. If not, If the resource has not been Modified, ETag (a unique identifier of the resource content, returned with the server response, If-none-match (The server compares the if-none-match in the request header with the ETag of the current resource to determine whether the resource has been modified between requests. If not, it matches the negotiation cache.)

The reason for using ETag instead of last-Modified is that in certain cases, static files may be updated frequently, but the contents of the file do not change. When last-Modified is used, the server always returns the latest contents to the browser. Etag is based on the content of the file, and if the content does not change, the browser will always use the locally cached file. Therefore, using ETag can better avoid some unnecessary server correspondence

Here’s the link: juejin.cn/post/694822…

4. Data transmission layer – compression

  • 1) Data compression gzip new BR
  • 2) Code files compress HTML/CSS/JS comments, Spaces, long variable names, etc
  • 3) Static resource font icon remove metadata reduce size and resolution, use JPG or WebP format

5. Header and packet

  • 1) Reduce unnecessary headers in HTTP1.1
  • 2) Reduce cookie data amount

1) Http2 header compression bloated request header average 460 bytes of the first dedicated HPACK compression algorithm

  • The index table
  • Huffman code

2) binary frames 3) link multiplexing

Ii. More efficient data processing tools tested AB III. Code optimization 1. HTML semantic tags to enhance DOM parsing 2. Do not use JS 3 if you can achieve the effect of HTML/CSS. Use more pseudo-elements, reduce js multiple DOM search traversal 4. Logic and display decoupling, avoid unnecessary JS engine startup 5. Reduce scope lookups and closures to avoid == using block-level scope four. Server side rendering SSR solution: Next-js nuxt.js

Concept: Make your page load faster! Ideas: analysis of a page from the input URL to page loading display complete all steps, using divide-and-conquer method step by step optimization. 1. Optimize DNS queries to reduce domain names: Try to place all resources under one domain name. A domain name can send 4 requests (IE8) or 8 requests (Chrome) simultaneously. Request file less, use 1 domain name, file multi domain name. Student: Trade-offs with 3. 2. Optimize TCP protocol 1) TCP connection reuse: keep-alive: indicates the connection reply and the request header: keep-alive. The first request is repeated and the second request is repeated. 2) Use HTTP 2.0: multiplexing, connection multiplexing rate will be higher 3. Optimize sending HTTP requests 1) merge JS or CSS files 2) Inline image: use data: URL scheme to inline images 3) Reduce cookie size. Cookies come with each request, so don't abuse cookies. 4) Use the CasheControl instead of sending HTTP requests. 5) Send multiple requests at the same time. IE8 can request four CSS files at a time, and Chrome can request eight CSS files at a time. 1) Set Etags: the browser repeats the same file as the requesting server, and ETag responds 304. Macos Gzip, NPM server Gzip Gzip file name. The response header is content-encodinging: Gzip. Disadvantages: browser CPU consumption, tradeoff 5. Optimized DOCTYPE can't write, can't write wrong 6. 1) Using CDN: using CDN to request static resources can increase the number of downloads at the same time, content distribution network (CDN) can reduce the total request time, also can reduce cookies 2) CSS in the head: 3) JS at the end of the body: show the whole page as early as possible to get nodes. 1) Component lazy loading const XXX =()=>import('./components/xxx.vue') 2) route lazy loading 8. Optimize user experience: 1) Users request what they see; 2) Adding a loading animation will make users feel the time is faster. 9. Reduce listeners, Use event delegation < body > < ul > < li > 1 < / li > < li > 2 < / li > < li > 3 < / li > < li > 4 < / li > < / ul > < script > let liList = document.querySelectorAll('li') // liList[0].onclick = ()=>console.log(1) // liList[1].onclick = ()=>console.log(2) // LiList [2]. The onclick = () = > console. The log (3) / / liList [3]. The onclick = () = > console. The log (4) / / a: Let ul = document.querySelector('ul') ul.onclick = (e) => {if (e.target.tagName === 'LI') { Console. log(e.target.innertext)}}// Method 2: Reduce listening, use the event delegate </script> </body> 10. Var elem = $('#elem'); for (var i = 0; i < 100; i++) { elem.append('<li>element '+i+'</li>'); } var elem = $('#elem'), arr = []; for (var i = 0; i < 100; i++) { arr.push('<li>element ' +i+'</li>' ); } elem.append(arr. join('')); // data.length === 100000 for(var I = 0; i < data.length; i++){ // do something... For (var I = 0,len = data.length; i < len; i++){ // do something... } 13. Use setTimeout to reduce the frequency of calling interfacesCopy the code

1. The hash pattern

Vue-router defaults to hash mode — the hash of a URL is used to simulate a full URL so that the page does not reload when the URL changes.

2. The history mode

If you don’t want ugly hashes, you can use the history mode of the route, which takes full advantage of the history.pushState API to do URL jumps without reloading the page. The history mode requires background configuration support

3.WebSocket

  1. HTTP is a short link, because after a request, the connection is closed, and the next time you request data, you have to open the connection again.
  2. The WebSocket protocol is a long connection that requires only one request to initiate the connection, and then all requests and responses are communicated through the TCP connection. WebSocket is an Internet technology that really realizes the full duplex communication from the server to the client. It is a full duplex communication protocol on a single TCP connection

Features:

(1) HTTP protocol is adopted in the handshake phase, and the default ports are 80 and 443

(2) based on TCP protocol, and HTTP protocol belongs to the application layer

(3) It can send text or binary data.

(4) There is no source restriction, and the client can communicate with any server.

(5) The protocol identifier is WS (WSS if encrypted), such as WS ://localhost:8023

4. Pure functions

A function whose returns depend only on its arguments and have no side effects is called a pure function. For example:

The return of a function depends only on its arguments. There are no side effects during function execution. Const foo = (a,b) => a + b foo(1,2) // => 3Copy the code

Blog.csdn.net/c_kite/arti…

What is the virtual DOM

Is a JS object that describes the real DOM,

The Virtual DOM is a programming concept. In this concept, the UI is kept in memory in an idealized, or “virtual,” representation, synchronized with the “real” DOM through libraries such as ReactDOM. This process is called coordination. The “Virtual DOM” is often associated with React elements because they are objects that represent the user interface. React also uses an internal object called “Fibers” to store additional information about the component tree.

6. React Fiber

Fiber is the new coordination engine in React 16. Its main purpose is to enable the Virtual DOM to perform incremental rendering: a method of breaking the rendering into blocks and spreading it out over each frame.

Other core features include suspension, termination, and continuation with new updates in the program; And prioritizing different tasks; And the latest concurrency

7. When is this.setState synchronized? When is it asynchronous?

Native events are synchronized with setTimeout

The execution of setState itself is synchronous, but because the execution sequence in react synthesis events and hook functions precedes the update, the updated value cannot be directly obtained, thus creating the so-called asynchronous.

8. React performance optimization

1. Make sure you are using a compressed production version. Note: React files ending with.production.min.js are suitable for production 3. Use the Chrome Performance TAB to analyze Component 4. Virtual Long Lists: Virtual scrolling technology. This technique renders only a limited amount of content in a limited amount of time, reducing the time it takes to re-render components, and the number of DOM nodes created. ShouldComponentUpdate 5. The power of immutable data

9.redux

Redux is a JavaScript state container that provides predictable state management, where all states in an application are stored in a single store as a tree of objects. The only way to change state is to trigger an action, an object that describes what happens. To describe how actions change the state tree, you need to write reducers, which have a single store and a root-level Reduce function (Reducer). As your application grows, you should split the reducers at the root level into smaller reducers that work independently on different parts of the state tree, rather than adding new stores. It’s like a React app that has only one root component, which in turn is made up of many widgets.

10. Advanced components

HOC is an advanced technique used in React to reuse component logic. HOC itself is not part of the React API; it is a design pattern based on the composite features of React. Specifically, a higher-order component is a function that takes a component and returns a new component. A component converts props to UI, and a higher-order component converts a component to another component

Practical application: Redux’s Connect

11.jsx

JSX just React. CreateElement (Component, props,… The syntactic sugar of the children function.

<MyButton color="blue" shadowSize={2}>
  Click Me
</MyButton>
Copy the code

Compiled into:

React.createElement(
  MyButton,
  {color: 'blue', shadowSize: 2},
  'Click Me'
)
Copy the code

12.Time Slice and Suspense?

Time Slicing

React does not block the current thread when rendering. If your device is fast enough, you will feel that the render is synchronized. If your device is very slow, you will feel sensitive and render asynchronously, but you will see the complete render, rather than a component rendered line by line in the same way that components are written

Suspense (also called pauses)

  • In the render function, we can write an asynchronous request requesting data
  • React will read this cache from our cache
  • If there is a cache, just render normal
  • If there is no cache, an exception is thrown, which is a promise
  • When the promise is complete, React will go back to render (essentially re-render) and render the data
  • Completely synchronous, without any asynchronous callback or anything like that

13. What is the biggest difference between the Observer model and the publish-subscribe model?

The biggest difference between the observer mode and the publish-subscribe mode is that the publish-subscribe mode has an event scheduling center.

As can be seen from the figure, in the observer mode, the observer and the target interact directly, while in the publish and subscription mode, the scheduling center handles the interaction uniformly, and subscribers and publishers do not interfere with each other. This allows for both decoupling and more fine-grained control. For example, if a publisher publishes a lot of messages, but does not want all subscribers to receive them, it can do some processing in the dispatch center, such as permission control. You can also do some throttling.

14. Temporary dead zones

A variable is not available within a code block until it is declared using the const let command. This is grammatically called a “temporary dead zone.”

15. Binary lookup tree features

The value of all nodes in the left subtree is less than or equal to the value of its root node. Left and right subtrees of binary sort tree respectively. Also blog.csdn.net/Strangerrai…

16. What are the advantages and disadvantages of the Transform animation versus directly using left and top to change positions

1. The left and top

Will vaguely feel the animation running is not smooth, animation some pause feeling. This is because top and left changes trigger reflow and repaint for the browser. Then the entire animation process is constantly triggering the browser to re-render, which can be very performance critical

2. The transform animation

Neither repaint nor reflow occurs during animation movement. Rationale: Ransform animation is gPU-controlled and supports hardware acceleration. zhuanlan.zhihu.com/p/78230297

17. How do I determine if two objects are equal in JavaScript

Blog.csdn.net/weixin_4379…

18 when callingsetStateWhen the ReactrenderHow does it work?

  • Virtual DOM Rendering: When the Render method is called, it returns the virtual DOM structure of a new component. When setState() is called, render is called again, because shouldComponentUpdate always returns true by default, so React is not optimized by default.

  • Native DOM rendering :React only modifies real DOM nodes in the virtual DOM, and only infrequently — this is a great React feature that optimizes changes to the real DOM and makes React faster.