Virtual DOM (DOM) Diff algorithm and key mechanism
Reference juejin. Cn/post / 684490…
- Virtual DOM
The Virtual DOM is an abstraction of the DOM, essentially a JavaScript object that is a more lightweight description of the DOM.
We all know that one of the secrets of performance optimization on the front end is to minimize DOM manipulation, not only because DOM is relatively slow, but also because frequent DOM changes can cause backflow or redraw of the browser, which can cause performance problems. Therefore, this layer of virtual DOM comparison is needed to update the differences into the DOM as much as possible at once, thus ensuring that the DOM does not suffer from poor performance.
For example, Node.js does not have the DOM. If you want to implement SSR(server-side rendering), one way is to use the Virtual DOM, because the Virtual DOM itself is a JavaScript object.
- The diff algorithm
When we actually developed React, we used the Render () function to create a React element tree that simulated a virtual DOM tree. On the next update of the state or props, a new React element tree is created, emulating a new virtual DOM tree. Once the two trees are simulated, the diff algorithm is used to compare the old and new trees before deciding how to modify the DOM. The traditional DIFF algorithm compares nodes in turn through cyclic recursion, which is inefficient. The algorithm complexity reaches O(n^3), while the complexity of reactO(n^3) is reduced to O(n).
- The key value
React uses a key to identify components, which is an identifier. React considers the same key as the same component. In this way, components corresponding to the same key will not be created again.
The value of key must be unique and stable. Unstable keys, such as the key math.random () generated by them, cause many component instances and DOM nodes to be recreated unnecessarily, which can lead to performance degradation and loss of state for child components
React updates only the component properties if the key is the same. No change, no update.
React destroys the component (stateful component constructor and componentWillUnmount) and re-creates the component (stateful component constructor and componentWillUnmount).
In project development, the most common use of the key attribute is to dynamically create child components from arrays, and to add a unique key attribute value to each child component
Do not use index as the key
For example
Array [1,2,3,4] and key with subscripts 0,1,2,3Copy the code
- So the diff algorithm finds the value 1 of key=0 in the array before the change, and 4 of key=0 after the change
- Re-delete and update the child elements because they are different
But if I add a unique key
Array [1,2,3,4]; array [4,3,2,1]; subscripts d,c,b,aCopy the code
- The diff algorithm finds the value of key=a in the array before the change and finds the value of key=a in the array after the change
- Because the child elements are the same, they are not deleted and updated. Only movement is done to improve performance.
Solution:
Globally define a variable: let ONE = 1 and then use key = {ONE++} in the component. In this way, the key changes every time when setState() is set, and the unstable nature of the key is avoided to a certain extent
React lifecycle
The React lifecycle is divided into three phases: mount, update, and uninstall
Mount:
- constructor
Called before the React component is mounted
When we implement the constructor for the react.componentsubclass, we should call super() before any other statements. Super is used to inherit this from the parent class to subclasses.
The React constructor is primarily used to initialize the internal state of the function and bind instances of the event handler.
You cannot call this.setState from inside the constructor function because the first render has not yet been executed and the DOM node has not yet been mounted
- static getDerivedStateFromProps
Called before the Render method is called, both during initialization and during subsequent updates
Return value: Returns an object to update state, or null to update nothing
Parameters: The first parameter is props for the update and the second parameter is state for the previous state. You can compare the two parameters to restrict conditions and prevent useless updates.
GetDerivedStateFromProps is a static function and cannot use this
- render
It is the only method that the class component must implement to render the DOM
Cannot setState in render, otherwise it will cause an infinite loop
- componentDidMount
After the component is mounted, you insert the DOM scaffolding call, where you can update state, set event listeners, AJAX requests, and so on
Update:
- static getDerivedStateFromProps
- shouldComponentUpdate
Called before the component is updated to control whether the component is updated or not, if true is returned, false is not updated
Parameter: The first parameter is the props to be updated, and the second parameter is the state to be updated. You can compare the props or state before and after the update and add some restrictions to determine whether to update the software for performance optimization.
Deep comparisons or using json.stringify () in shouldComponentUpdate() are not recommended. This is very inefficient and can hurt performance
Do not call setState() directly in shouldComponentUpdate as this will cause an infinite loop of updates and renders until the browser memory crashes
You can use built-in PureComponent components instead or use third party libraries (react-immutable-render-mixin)
React-immutation-render -mixin uses immutation-jsis () to compare data from complex types. It is similar to PureComponent in that it uses immutation-jsis () to compare data from complex types. More convenient than react. PureComponent
The react.pureComponent is almost identical to the react.componentponent, but the react.pureComponent shouldComponentUpate() by using a shallow contrast between props and state. If the object contains complex data structures, it may generate false negative judgments due to inconsistencies in deep data (for example, the view of the object’s deep data has been changed but not updated)
According to the above rules, we can make the following optimization in project development:
Try to separate views associated with complex type data into PureComonent to improve rendering performance, such as forms, text fields, and complex lists in the same render(), and input field changes in the form field will frequently trigger setState() causing the component to rerender (). The data used to render a complex list doesn’t actually change, but the list is still re-rendered due to the refiring of render().
- render
- getSnapshotBeforeUpdate
Called before the last render output is committed. That is, after render, when the component is about to be mounted.
It allows the component to capture some information (such as scroll position) before the DOM is actually updated, and any values returned by this lifecycle are passed as arguments to componentDidUpdate(). Return NULL if no value needs to be passed
- componentDidUpdate
Will be called immediately after the update. The first render will not be executed
Contains three parameters, the first of which is the previous props value. The second is the last state value. If the component implements the getSnapshotBeforeUpdate() life cycle, the third is the “snapshot” parameter passing
Uninstall:
- componentWillUnMount
Called when a component is about to be uninstalled or destroyed, you can cancel network requests, remove listening events, clean up timers, and so on during this lifecycle.
In React16 componentWillMount, componentWillReceiveProps, componentWillUpdate has been abandoned.
Why was it scrapped? This is react Fiber in React 16
What is React Fiber
Due to the single-threaded nature of JS, you cannot allow each synchronization task to take too long, or the program will not respond to other inputs. The React update process violates this taboo, and in order to change this, Fiber was introduced.
Fiber reconstructs the core algorithm of React. Use the browser requestIdleCallback method
Window. RequestIdleCallback () method will be a (the) function to be executed by the browser in the spare time to join the queueCopy the code
Interruptible tasks are sharded so that each small piece runs for a short time so that a single thread is not monopolized.
Because the process may pause and then continue, the lifecycle hooks may not execute or execute multiple times, thus losing the purpose of the abandoned hook functions. Using setState in the abandoned hook functions may also trigger multiple redraws, affecting performance.
React Hooks
Hooks are a new addition to Act 16.8 that allow you to use state and other React features without writing classes. Using Hooks, you can extract stateful logic from components so that it can be tested and reused independently.
Will Hooks replace Render props and higher-order components
Currently not, hooks cannot share component state logic. But Hooks are sufficient in most cases to reduce nesting in the tree and improve performance.
- React Hooks what are the benefits of React Hooks
1. Class definitions are more complex
Different life cycles will make the logic scattered and chaotic. Always pay attention to the pointing problem of this. Code reuse is more expensive, and the use of higher-order components will make the whole component tree become bloatedCopy the code
2. State is isolated from THE UI. Because of Hooks, the state logic becomes much smaller in granularity and can easily be abstracted into a custom Hooks, making the state and UI in components much clearer and more isolated.
- Why can’t Hooks be called in loops, conditions, or nested functions
React raises an error. React uses a linked list to ensure that the hooks are in strict order. Conditional loops or nested functions, which can cause order changes, should not be included.
- Name a few common hooks
1. UseState: Defines the State of the component
2. UseEffect: There are many lifecycle functions in the class definition, and a corresponding function (useEffect) is provided in React Hooks, ComponentDidMount, componentDidUpdate and componentWillUnmount
UseContext: Obtains the context object
4. UseCallBack: The function is cached, so that the incoming callback will not be a new function instance each time, resulting in the re-rendering of dependent components, which has the effect of performance optimization
5. UseMemo: Caches the results returned by functions to avoid dependent components being re-rendered each time
6. UseRef: Obtain the real node of the component
7. UseReducer: Provides functions similar to Redux
- useEffect
UseEffect can be seen as the combination of componentDidMount, componentDidUpdate and componentWillUnmount. UseEffect (callback, [source]) takes two arguments
1. The useEffect hook function is executed every time any data in the component changes.
2. Pass an empty array, which will be called once during initialization
3. If the hook function has a value, it listens for the value change and re-executes the hook function.
- useReducer
UseReducer is essentially a pure function without any UI or side effects. It takes two arguments, the first one receiving the function and the second one receiving the initialized value. The function always returns a new state, which can be updated using destruct assignment. It also has an action parameter, which uses type to represent the specific type of action and payload to provide data information about the operation.
The difference between the Class component and Hooks
- The most obvious difference is that the syntax is different and the function component is just a generic one
js
Object, which can returnJSX
. A class component is an inheritanceReact.Component
theJS
Class, it has onerender
function - Component parameters are passed as function parameters in function components. In a class component, you need
this
To refer to. - To deal with
state
Unlike before, it can only be handled in the class componentstate
In theReact16.8
In, citedreact hook useState
, allowing developers to writestate
Function component of - Different life cycles, class components do
componentDidMount
Lifecycle, in function components, we useuseEffect hook
To replace thecomponentDidMount
.
React Indicates the communication mode of the component
-
The parent component passes the required information to the child component via props
-
The child component binds methods in this.props, and the parent component receives methods
-
Components pass props across layers of components, use context, and communicate with global mechanisms such as Redux and MOBx
What is a Context:
Context provides a way to pass data through the component tree, eliminating the need to manually pass props layer by layer.
The react principle of the router
Reference juejin. Cn/post / 688629…
First of all, we need to know what single application is. In fact, it is to use an HTML, load JS, CSS and other resources at one time. All pages are under a container page.
React-router-dom and the react-router library
**history** can be understood as the core of the react-router, and is also the core of the entire routing principle, which integrates popState, history.pushState and other low-level routing implementation principles and methods.
**react-router-dom** react-router-dom** react-router-dom** react-router-dom** Switch and other core components realize core functions from routing changes to component updates. In our project, we only need to introduce react-router-DOM once.
** React-router-dom ** adds Link components for jump, BrowserRouterh in histoy mode and HashRouter in hash mode to the core of react-Router. **BrowserRouter and HashRouter are just createBrowserHistory and createHashHistory methods from the history library
Principle of History Mode
- Change the routing
History. PushState, history. ReplaceState
- Listening to the routing
The PopState event is emitted when the history object of a document changes. History. pushState allows the browser address to change without refreshing the page. The popState event is not triggered by history.pushState() or history.replacestate (). The popState event is only triggered when the browser does something, such as clicking the back or forward button or calling the history.back(), history.forward(), or history.go() methods.
Principle of Hash Mode
- Change the routing
Get and set the hash value using the window.location.hash property.
- Listening to the routing
Window.addeventlistener ('hashchange',function(e){/* Listen for changes */})
** History ** provides core apis such as listening to routes, methods to change routes, and saving route state.
** React-router ** Provides route rendering components, route unique matching components, redirection components, and other functional components.
When the address bar changes the URL, what happens to the updated rendering of the component?
Take the History schema as a reference. When a URL changes, it first fires histoy, calls events to listen for popState events, fires the handlePopState callback, fires the setState method under history, generates a new location object, The Router component is then notified to update the location and pass it through the context context. The Switch matches the matching Route component rendering through the passed update stream. Finally, the Route component extracts the context content and passes the rendering to update the page.
When we callhistory.push
What about methods, switching routes, and updated rendering of components?
When we call history.push, we call the push method of history first, change the current URL with history.pushState, and then fire the setState method under history. The next steps are exactly the same as above, which is not explained here.
Redux
Reference juejin. Cn/post / 684490…
What a Redux is:
Redux is a state management library for React that is based on Flux. Redux simplifies one-way data flows in React. It abstracts state management completely from React.
Redux
Yes, born to giveReact
Applications provide “predictable state management” mechanisms.Redux
The entire application state (that is, data) is stored in a place calledstore
- this
store
It keeps a state tree inside(state tree)
- Component change
state
The only way is by callingstore
thedispatch
Method to trigger aaction
theaction
By the correspondingreducer
Deal with, thenstate
To complete the update - Components can be distributed (
dispatch
) (action
) tostore
Instead of notifying other components directly - Other components can be subscribed
store
State in (state
) to refresh your view
How redux works:
In React, the component connects to redux. To access redux, it sends an action containing its ID and payload. Payload in the action is optional, and the action forwards it to the Reducer.
When reducer receives the action, swithc… Case syntax compares type in action. When a match is made, updating the corresponding content returns the new state.
When the Redux state changes, components connected to the Redux will receive the new state as props. When the component receives these props, it goes into the update phase and rerenders the UI.
How does Redux handle asynchrony
1. The store dispatches action to update data. This action is synchronous.
2. The so-called asynchronous Action is implemented after the dispatch enhancement by introducing middleware solutions. ApplyMiddleware returns dispatches that override the original store and, when action is a function, custom dispatches for asynchronous scenarios.
3. In my opinion, the reason for adopting this middleware enhanced mode is that it is centralized in one location to facilitate unified control and processing, and the other is to reduce redundant judgment templates in the code.
Mobx
Reference juejin. Cn/post / 685041…
His principle was simple:
In Mobx, the essence is to have a parent component on top of the component that uses the observed data, and the parent component is a stateful component. The Observer mode is then used to notify the Observer when a data change is detected, and the Observer calls setState to update the Observer, thereby finally refreshing the child components.
-
The event calls Actions, which is the only function that allows changing state and may have other side effects.
-
Then modify State. It is an observable set of states and should not contain redundant data (such as states that will not be updated)
-
Updated Computed Value is pure functions that return values that can be derived from state
-
Triggering Reactions is similar to Computed Value, and it allows for side effects (such as UI state updates)
Common decorator
-
Observable makes a variable observable
-
The @Observer is used by the React component to monitor observable variables used in the Render function to make reactions
-
Autorun is commonly used in component or store constructor classes to create instances by monitoring observable variables used in their function arguments to make reactions, typically by executing the function again.
-
@when conditional @autorun
-
@ Computed Values calculated by pure functions of observable variables are computed only when they are used, not when they are not
-
@action An operation that changes the value of an observable variable (usually a function method)
Mobx vs. Redux
-
In Redux’s view, data consistency is very important. In order to maintain data consistency, data in stores should be formalized as much as possible, that is, to reduce all unnecessary redundancy. In order to limit data modification, data in stores should be Immutable. The Reducer can only be triggered by action to update the Store.
-
Mobx agrees that data consistency is important, but it believes that the fundamental solution to the problem is not to formalize data, but to not give it the opportunity to become inconsistent. As a result, Mobx encourages data to be “de-canonized,” and redundancy is fine. As long as all data is linked and the data that depends on it is updated automatically, data inconsistencies will not occur.
Although one of Mobx’s initial selling points was to modify data directly, in practice this was found to be disorganized and undisciplined, so Mobx later introduced the concept of Action. A bit different from Redux’s action, Mobx’s action is actually a function that doesn’t need to be dispatched.
To force action, don’t modify Observable data directly. Use Mobx configure as follows:
import {configure} from 'mobx';
configure({enforceActions: true});
Copy the code
To summarize the differences between Redux and Mobx, including these aspects:
-
Redux encourages one Store for an app, while Mobx encourages multiple stores.
-
Redux uses pull to use data, which is consistent with React, but Mobx uses push to use data, which is closer to tools like RxJS.
-
While Redux encourages data formalization and reduces redundancy, Mobx allows data redundancy but still keeps data consistent.
SetState
1. Composite events
When it comes to setState, first of all, we need to understand what synthetic events are. Synthetic events are a set of event mechanisms packaged by React in order to solve cross-platform and compatibility problems. React agents native events, such as onClick and onChange in JSX, are synthetic events. In the try finally syntax of the source. SetState is executed inside a try, and finally is executed after the try is complete. This is when you update your state and render it to the UI, so calling setState in a composite event will not immediately get the value of state, leading to asynchrony. However, the updated value can be retrieved via setState’s callback function.
2. Life cycle
React does not update componentDidmount until after it executes. So you don’t get setState right away in componentDidmount
3. Native events
Native events are non-React synthesized events, such as native events that listen to addEventListener, or bind events such as document.querySelector().onclick.
The call stack of the native event is relatively simple, without a lot of logic to synthesize the event, it will directly trigger the click event, so after setState in the native event, you can get the updated state value synchronously.
4. setTimeout
SetTimeout can be used in many situations, such as synthetic events, hook functions, and native events. However, in any scenario, under the event loop-based model, setState in setTimeout can always get the latest state value.
Conclusion:
setState
Is “asynchronous” only in synthesized events and hook functions, in native events andsetTimeout
All of them are synchronized.setState
“Asynchronous” is not to say within the asynchronous code implementation, execution process and actually are synchronized code, just synthetic events and hook function call order before update, resulting in synthetic events and hook function can not immediately get the updated value, form the so-called “asynchronous”, can, of course, by the second argumentsetState(partialState, callback)
In thecallback
Get the updated results.setState
Batch update optimization is also based on “asynchrony” (composite events, hook functions), and on native events andsetTimeout
Does not batch update, in “asynchronous” if the same value multiple timessetState
,setState
The batch update policy overwrites it and takes the last execution, if at the same timesetState
Multiple different values that are merged and updated in batches when updated.
When callingsetState
When,React render
How it works:
-
The first is virtual DOM rendering: when the Render method is called, it returns a new virtual DOM structure. When setState() is called, render is called again, because shouldComponentUpdate always returns true by default, so React is not optimized by default.
-
Then there’s native DOM rendering: React only modifies real DOM nodes in the virtual DOM, and very rarely — this is a great React feature that optimizes changes to the real DOM and makes React faster.
Refs
What does refs in React do
Use Refs on the DOM node or React element to access the node. In general, props is the only way for parent and child components to interact, and to modify a child component, you need to render it with new props. However, Refs can be used when we want to force changes to children under certain circumstances.
How do I create Refs
Created with react.createref () in the class component and useRef in the function component. Add the REF attribute to the React element, which uses refs to pass event data to the parent component.
Refs Usage scenario
In some cases, we might need to modify the subitem without rerendering it with new props, so we would use refs, for example:
- Integration with third-party DOM libraries
- Trigger imperative animation
- Manage focus, text selection or media playback
The scenario
Reference juejin. Cn/post / 684490…
React.createRef()
: When we build a button, the page automatically focuses on the input field when clicked- from
Ref
When we create ainput
Box to enter the value, and then click the Submit button to read the value Refs
Callback: when we setRef
When,React
Will call this function and willelement
Pass it as the first argument. You can also get it this wayinput
The text value of the tag- Forwarding Refs:
Ref forwarding
: Reuse component libraries and higher-order components
How do you handle events in React
To address cross-browser compatibility, React provides SyntheticEvent, a cross-browser native event wrapper. It also has the same interface as browser native events, including stopPropagation() and preventDefault().
React doesn’t actually attach events to child nodes themselves. It uses a single event listener to listen for all events at the top level. This is good for performance and means React doesn’t need to track event listeners when updating the DOM.
Event mechanism:
- When the user is in the
onClick
When I add a function,React
Did notclick
Event binding toDOM
on - But in the
document
To listen for all supported events when an event occurs and bubbles todocument
Place,React
Encapsulate the event content to the middle tierSyntheticEvent
(Responsible for the synthesis of all events) - So when an event is triggered, the pair uses a uniform distribution function
dispatchEvent
The function execution will be specified.
What’s the difference between props and state
Props and state are plain JS objects. Although they both affect the information rendered output, their component-wise functionality is different.
state
It is the component that manages its own data, controls its own state, and is mutableprops
Is an external data parameter that is immutable- There is no
state
The stateless component is called the stateless componentstate
Is called a stateful component - multi-purpose
props
Use less,state
That is, write more stateless components
How to avoid component rerendering
React.memo()
Avoid unnecessary rendering of function componentsPureComponent
: Avoid unnecessary rendering of class components
Both methods rely on a shallow comparison of the props passed to the component, and if the props are not changed, the component will not be rerendered. While both tools are useful, shallow comparisons can lead to an additional performance penalty, so both can have a negative impact on performance if used improperly.
We can measure performance using the React Profiler
What are higher-order components
Reference juejin. Cn/post / 684490…
Higher-order components are not components; they are enhancements. A function is called a higher-order component if it takes one or more components as arguments and returns a component. ,
Form of higher-order components:
1. Property proxyprops proxy
Function HigherOrderComponent(WrappedComponent) {return props => <WrappedComponent {... props} />; Function HigherOrderComponent(WrappedComponent) {return class extends React.Component {render() {function HigherOrderComponent(WrappedComponent) {return class extends React.Component {render() { return <WrappedComponent {... this.props} />; }}; }Copy the code
2. Reverse inheritance
function HigherOrderComponent(WrappedComponent) { return class extends WrappedComponent { render() { return super.render(); }}; }Copy the code
Disadvantages of higher-order components:
1. Static method missing:
Because the original component is wrapped in a container component, this means that the new component does not have any static methods of the original component
Refs attribute cannot pass through: ** In general, higher-order components can pass all props to wrapped components, but there is one attribute that cannot be passed, and that is ref.
- It’s different from the other attributes
React
It is treated with special treatment. If you add to an element of a component created by a higher-order componentref
Quote, thenref
Refers to the outermost container component instance, not the wrapped oneWrappedComponent
Components. So if you have to pass it onref
Words,React
Provides us with a program calledReact.forwardRef
的API
To solve this problem
3. Reverse inheritance does not guarantee that the entire tree of subcomponents will be parsed: React components come in two forms: class and function (stateless components). Render hijacking like reverse inheritance controls the WrappedComponent rendering process, which means we can do various things to the results of elements Tree, state, props, or render(). However, if the rendering elements Tree contains a component of type function, then the child components of the component cannot be manipulated.
HOC can be used for many use cases
- Code reuse, logic, and bootstrap abstraction
- Rendering hijacked
- State abstractions and operations
- Props to deal with
HOC application scenarios
-
The conditional rendering feature of higher-order components can be used to control page permissions, which are generally divided into two dimensions: page level and page element level
-
The rendering time of a component can be easily recorded by capturing the life cycle of a child component with the parent component’s child component’s life cycle rule
-
Page reuse
What is the function of calling super in the constructor and passing props as an argument?
The subclass constructor cannot use this until super is called. This.props can be used in state after this call
What are controlled components and uncontrolled components
- A state-controlled component is required
onChange
Method, otherwise cannot be used. Controlled components can be assigned default values (controlled components are recommended) for two-way data binding - An uncontrolled component means I don’t need to set it
state
Properties, while throughref
To manipulate the realDOM
What is the difference between a controlled component and an uncontrolled component?
- The controlled component is
React
Control component, and is the only true source of form data - Uncontrolled components are made up of
DOM
Where the form data is processed, not inReact
In the component
Although uncontrolled components are usually easier to implement because you can simply use refs to get values from the DOM, it is often recommended to prefer controlled components to uncontrolled ones. Because controlled components support instant field validation, they allow conditional disabling of enable buttons, mandatory input formats, and so on.
What is the JSX
JSX emashes raw HTML templates into JS code. The JSX code itself cannot be read by browsers and must be converted to traditional JS using tools such as Babel and Webpack
What is strict mode in React
React is an auxiliary component that helps you write a better React component.
- Verify that internal components follow certain recommended practices
- Verify that deprecated methods are used
- Identify potential risks and prevent some side effects
What is Prop Drilling and how to avoid it
When you have multiple nested components that need to use data from the source component, the easiest way to do this is to pass props layer by layer, from the source component to the deep nested component. This is called Prop Drilling
To avoid it, a common way is to use React. CreactContext or useContext. By defining Provider components that provide data, you allow nested components to obtain source data
Describes Flux and MVC
The traditional MVC pattern does a good job of separating data, but the MVC architecture often runs into two major problems:
- Data flow is not clear: Cascading updates across views often result in a chaotic web of events that are difficult to debug.
- Lack of data integrity: Model data can conflict anywhere and thus throughout
UI
To create unpredictable conditions
Complex user interfaces using Flux mode are no longer subject to cascading updates, and any given React component is able to reconstruct its state from the data provided by the Store. The Flux pattern also enforces data integrity by limiting direct access to shared data
How do I apply validation to Props of ReactJS
In development mode, React automatically checks components that have props set up to ensure that they have the correct data type. For incorrect data types, a warning message is generated in the console, but it is disabled in production mode due to performance impact. The mandatory props is defined with isRequired.
What’s the difference between using constructors in React and getInitialState
The essential difference is the difference between ES6 and ES5
class MyCom extends React.Component{
constructor(props){
super(props);
this.state={}
}
}
Copy the code
Is equivalent to:
var MyCom = React.createClass({
getInitialState(){
return{}
}
})
Copy the code
What is a pure function
Pure functions are functions that do not depend on, and do not modify the state of a variable outside of its scope.
Essentially, pure functions always return the same result given the same parameters
How do I avoid rebinding instances in React
- Use inline arrow functions or arrow functions
- Use a
Hooks
Function component of
React elements vs. components
- React element
It is the smallest basic unit in React, and we can create a React element using JSX syntax
The React element is not a real DOM element; it is just a normal JS object, so there is no way to call the DOM native API directly
In addition to the JSX syntax, we can also build React elements using react.createElement () and react.cloneElement ()
- The React components
React builds components: react.createclass (), ES6class, stateless function, PureComponent
- The difference between elements and components
Components are made up of elements, which are ordinary objects, and components, which are classes or pure functions
What is state promotion
React is often used when several components need to share state data. In this case, it is best to manage these shared states by promoting them to their nearest parent, which is called state promotion.
What is Portal in React
It provides a way to render child nodes to DOM nodes other than the parent component
ReactDOM.createPortal(child, container)
Copy the code
The first argument is any renderable React child elements. The second argument is a DOM element.
What are Error Boundaries for React16
This is to prevent JS errors in part of the UI from ruining the entire application.
How do I use innerHTML in React
Add the dangerouslySetInnerHTML attribute and pass in the object’s attribute name _html
function App (props) {
return <div dangerouslySetInnerHTML={{_html:'<span>1</span>'}}></div>
}
Copy the code
What is the Reconcilation stage and the COMMIT stage in the React16 version
-
The first stage is mainly to do diff calculation on current tree and New Tree to find out the changing part. To traverse, compare, etc.
-
The COMMIT phase is a series of DOM operations that apply the captured changes to the real DOM tree. Not only do more complex DOM states have to be maintained, but continuing after an interruption can have an impact on the user experience.