Other chapters:

  • HTML & CSS
  • Javascript Part 1
  • Javascript Part 2
  • Vue part
  • The React part
  • Network part
  • Part of the performance

React

What is the virtual DOM?

The virtual DOM (VDOM) is an in-memory representation of the real DOM. The REPRESENTATION of the UI is kept in memory and synchronized with the actual DOM. This is a step that takes place between the rendering function being called and the element being displayed on the screen, and the whole process is called reconciliation.

What is the difference between a class component and a function component?

  • Class componentsOther features, such as status, can be usedstateAnd lifecycle hooks.
  • When the component just receivespropsWhen rendered to a page, stateless components are functional components, also known as dumb or presentation components.

Of course, there is a difference between a function component and a class component, and the performance of a function component is higher than that of a class component, because a class component is instantiated when it is used, whereas a function component simply executes the function and returns the result. To improve performance, use functional components whenever possible.

The difference between Function component Class components
Is there athis There is no There are
Whether there is a life cycle There is no There are
Stateful or notstate There is no There are

React refs for what?

Refs provides a way to access DOM nodes or React elements created in the Render method. In a typical data flow, props is the only way parent-child components can interact, and to modify the child component, you need to re-render it with new Pros. There are exceptions to this rule, and in some cases we need to force changes to children outside of the typical data stream. Refs can be used in this case.

We can use this by adding a ref attribute to the component, whose value is a callback function that receives the underlying DOM element or mount instance of the component as its first argument.

class UnControlledForm extends Component { handleSubmit = () => { console.log("Input Value: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => This. Input = input} /> <button type='submit'> submit </button> </form>)Copy the code

Notice that the input element has a ref attribute whose value is a function. The function takes the actual DOM element of the input and places it on the instance so that it can be accessed inside the handleSubmit function.

It is often misunderstood that refs can only be used in class components, but refs can also be used with function components by utilizing closures in JS.

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}
Copy the code

What’s the difference between props and state?

Props and state are plain JS objects. Although they both contain information that affects the rendered output, their component-wise functionality is different. namely

  • stateComponents manage their own data, control their own state, variable;
  • propsIs an external data parameter, immutable;
  • There is nostateThe stateless component is called the stateless componentstateAre called stateful components;
  • multi-purposepropsUse less,stateThat is, write more stateless components.

How do I create refs

Refs are created using react.createref () and attached to the React element via the ref attribute. When components are constructed, Refs are typically assigned to instance properties so that they can be referenced throughout the component.

class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; }} Copy the codeCopy the code

Or use it this way:

class UserForm extends Component {
  handleSubmit = () => {
    console.log("Input Value is: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} /> // Access DOM input in handle submit
        <button type='submit'>Submit</button>
      </form>
    )
  }
}
Copy the code

What are higher-order components?

HOC is a function that takes a component and returns a new one. Basically, this is a pattern derived from the React composite feature, which calls them * pure components because they can accept any dynamically supplied subcomponents without modifying or copying any behavior in the input component.

const EnhancedComponent = higherOrderComponent(WrappedComponent); Copy the codeCopy the code

HOC can be used in many of the following use cases

  • Code reuse, logic, and bootstrap abstraction
  • Rendering hijacked
  • State abstractions and operations
  • Props to deal with

What is a control component?

In HTML, form elements such as,, and ‘usually maintain their own state and are updated based on user input. When the user submits the form, the values from the above elements are sent along with the form.

React works differently. The component that contains the form tracks the input value in its state and rerenders the component every time a callback function (such as onChange) fires, as the state is updated. The input form elements whose values are controlled by React in this way are called controlled components.

What is JSX?

When Facebook first released React, they also introduced a new JS dialect, JSX, that embedded 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. Many developers will be able to use JSX unconsciously because it’s already integrated with React.

class MyComponent extends React.Component { render() { let props = this.props; return ( <div className="my-component"> <a href={props.url}>{props.name}</a> </div> ); }}Copy the code

Why not just updatestate

If you try to update state directly, the component will not be rerendered.

// error this.state. message = 'Hello world'; Copy the codeCopy the code

The setState() method is used to update the state. It schedules updates to the component state object. When state changes, the component responds by rerendering:

This.setstate ({message: 'Hello World'});Copy the code

What are the different phases of the React component lifecycle?

There are four distinct phases in the component lifecycle:

  1. Initialization: During this phase, the component is ready to set its Initialization state and default properties.
  2. MountingThe React component is ready to mount into the browser DOM. This phase includescomponentWillMountandcomponentDidMountLifecycle methods.
  3. UpdatingDuring this phase, the component is updated in two ways, sending new props and state. This stage includesshouldComponentUpdate,componentWillUpdateandcomponentDidUpdateLifecycle methods.
  4. UnmountingAt this stage, the component is no longer needed and is unloaded from the browser DOM. This phase involvescomponentWillUnmountLifecycle methods.

In addition to the four common life cycles above, there is another error-handling phase:

Error Handling: At this stage, this component is invoked whether an Error occurs during rendering, in a lifecycle method, or in the constructor of any child component. This phase contains the componentDidCatch lifecycle method.

What are the React lifecycle methods?

ComponentWillMount: Executed before rendering for app-level configuration in the root component.

ComponentDidMount: Executed after the first rendering, this is where you can make AJAX requests, DOM manipulation or status updates, and set up event listeners.

ComponentWillReceiveProps: do not perform when initializing render, it will undergo in the component to the new state (Props) is triggered, commonly used in the parent component state update subcomponents of rendering

ShouldComponentUpdate: Determines whether to update the component. By default, it returns true. If it is determined that the component does not need to be re-rendered after the state or props update, return false, which is a way to improve performance.

ComponentWillUpdate: Executed before shouldComponentUpdate returns true to determine the component to be updated.

ComponentDidUpdate: This is primarily used to update the DOM in response to props or state changes.

ComponentWillUnmount: This is used to cancel any network requests or remove any event listeners associated with the component.

What are the benefits of using React Hooks?

First, Hooks generally enable extraction and reuse of stateful logic that is common across multiple components without the burden of higher-order components or rendering props. Hooks can easily manipulate the state of function components without needing to convert them to class components.

Hooks do not work on classes. By using them, you can completely avoid using life cycle methods such as componentDidMount, componentDidUpdate, componentWillUnmount. Instead, use built-in hooks like useEffect.

React Hooks?

Hooks are new additions in React 16.8. They allow the use of 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. Hooks allow us to reuse stateful logic without changing the component hierarchy, making it easy to share Hooks between many components or with the community.

The React ofuseState()What is?

Here’s what useState(0) is for:

. const [count, setCounter] = useState(0); const [moreStuff, setMoreStuff] = useState(...) ; . const setCount = () => { setCounter(count + 1); setMoreStuff(...) ; . }; Copy the codeCopy the code

UseState is a built-in React Hook. UseState (0) returns a tuple where the first argument count is the current state of the counter, and setCounter provides methods to update the state of the counter.

We can use the setCounter method to update the count state anywhere – in this case, we can do more with it inside the setCount function. Using Hooks keeps our code more functional and avoids using class-based components too much.

What is Prop Drilling and how to avoid it?

When building a React application, you nest components in multiple layers to use data provided by another nested component. The simplest way to do this is to pass a prop layer by layer from each component, from the source component to the deep nested component. This is called Prop Drilling.

The main disadvantage of Prop Drilling is that components that do not require data become unnecessarily complex and difficult to maintain.

To avoid prop drilling, a common approach is to use React Context. By defining a Provider component that provides the data, and allowing nested components to useContext data through the Consumer component or useContext Hook.

Describe Flux versus MVC?

The traditional MVC pattern works well in separating data (Model), UI(View, and logic (Controller), 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 mutate anywhere, resulting in unpredictable results throughout the UI.

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.

What is the difference between a controlled component and an uncontrolled component?

  • The managed component is the component in React control and is the only real source of form data.
  • The uncontrolled component is where the DOM processes the form data, not in the React 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 choose controlled components over uncontrolled ones.

The main reason for this is that the controlled component supports instant field validation, allows conditionally disabling/enabling buttons, and enforces input formats.

What is React Context?

Context provides a way to pass data through the component tree, eliminating the need to manually pass props properties at every level.

How to avoid component rerendering?

One of the most common problems with React is that components unnecessarily rerender. React provides two methods that are useful in these situations:

  • React.memo(): This prevents unnecessary rerendering of function components
  • PureComponent: This prevents unnecessary re-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.

Using the React Profiler, you can measure performance before and after using these methods to ensure that you are actually improving performance by making a given change.

What is a pure function?

A pure function is a function that does not depend on and does not change the state of a variable outside its scope. Essentially, pure functions always return the same result given the same parameters.

When callingsetStateWhen the ReactrenderHow does it work?

We can divide “render” into two steps:

  1. Virtual DOM rendering: whenrenderWhen the method is called, it returns the virtual DOM structure of a new component. When callingsetState()When,renderWill be called again, because by defaultshouldComponentUpdateAlways returnstrueSo React is not optimized by default.
  2. 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.