Summary of common react interview questions

Source: Internet
Author: User
Tags es6 class
Already open-source

Address: https://github.com/nanhupatar...
Follow our team:

What is the role of keys in react?

Keys are secondary identifiers used by react to track which elements in the list are modified, added, or removed.

render () {
  return (
    <ul>
      {this.state.todoItems.map(({item, key}) => {
        return <li key={key}>{item}</li>
      })}
    </ul>
  )
}

In the development process, we need to ensure that the key of an element is unique among its same-level elements. In the react diff algorithm, react uses the key value of an element to determine whether the element is a newly created or moved element, thus reducing unnecessary element re-rendering. In addition, react also uses key values to determine the relationship between elements and local States. Therefore, we must not ignore the importance of keys in conversion functions.

What happens after setstate is called?

After the setstate function is called in the code, react merges the passed parameter object with the current state of the component and triggers the so-called reconciliation ). After the reconciliation process, react constructs a REACT element tree in a relatively efficient manner based on the new State and re-renders the entire UI interface. After react obtains the element tree, react automatically calculates the node differences between the new tree and the old tree, and then minimizes the re-rendering of the interface based on the differences. In the differential computing algorithm, react can relatively accurately know which locations have changed and how they should be changed. This ensures that on-demand updates are not all re-rendered.

React lifecycle Functions
  • Initialization phase:

    • Getdefaproprops: obtains the default attributes of an instance.
    • Getinitialstate: obtains the initialization status of each instance.
    • Componentwillmount: The component is about to be loaded and rendered to the page.
    • Render: The component generates a virtual Dom node here.
    • Componentdidmount: After a component is loaded
  • Running status:

    • Componentwillreceiveprops: called when a component receives an attribute
    • Shouldcomponentupdate)
    • Componentwillupdate: attributes and status cannot be modified when the component is about to be updated.
    • Render: component re-profiling
    • Componentdidupdate: the component has been updated.
  • Destruction stage:

    • Componentwillunmount: The component is about to be destroyed.
What is shouldcomponentupdate? (which periodic function is react performance optimization ?)

Shouldcomponentupdate is used to determine whether to call the render method to re-depict the Dom. Dom profiling consumes a lot of performance. If we can write a more optimized Dom diff algorithm in the shouldcomponentupdate method, we can greatly improve the performance.

Refer to react Performance Optimization-SF

Why does virtual Dom improve performance? (Required)

The virtual Dom is equivalent to adding a cache between JS and the real Dom. The Dom diff algorithm is used to avoid unnecessary Dom operations and thus improve the performance.

Use the JavaScript Object Structure to represent the structure of the DOM tree. Then use this tree to construct a real DOM tree and insert it into the document to reconstruct a new object tree when the state changes. Then compare them with the new and old trees, record the differences between the two trees, apply the differences between the two records to the real DOM tree built in step 1, and the view is updated.

Refer to how to understand virtual Dom? -Zhihu

React diff Principle)
  • Break down the tree structure by hierarchy and compare only the same-level elements.
  • Add unique key attributes to each unit in the list structure for convenient comparison.
  • React will only match the component of the same class (the class here refers to the component name)
  • Merge operation. When the setstate method of component is called, react marks it as dirty. After each event cycle ends, react checks all components marked with dirty for re-drawing.
  • Select Sub-tree rendering. Developers can override shouldcomponentupdate to improve diff performance.

Reference: React diff Algorithm

What is the role of refs in react?

Refs is the secure access to DOM elements or the handle of a component instance provided by react. We can add the ref attribute for the element and then accept the handle of the element in the DOM tree in the callback function. This value will be returned as the first parameter of the callback function:

class CustomForm 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>
    )
  }
}

The input field in the above Code contains a ref attribute. The callback function declared for this attribute will receive the DOM element corresponding to the input, we bind it to the this pointer for use in other class functions. It is also worth mentioning that refs is not exclusive to Class components. function components can also store their values using closures:

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}
If you have created a Twitter element like the following, what is its class definition?
<Twitter username='tylermcginnis33'>
  {(user) => user === null
    ? <Loading />
    : <Badge info={user} />}
</Twitter>
import React, { Component, PropTypes } from 'react'
import fetchUser from 'twitter'
// fetchUser take in a username returns a promise
// which will resolve with that username's data.
class Twitter extends Component {
  // finish this
}
 

If you are not familiar with the callback rendering mode (render callback pattern), this Code may look a bit strange. In this mode, the component receives a function as its sub-component and calls it in the rendering function with props. Children:

<Twitter username='tylermcginnis33'>
  {(user) => user === null
    ? <Loading />
    : <Badge info={user} />}
</Twitter>
import React, { Component, PropTypes } from 'react'
import fetchUser from 'twitter'
// fetchUser take in a username returns a promise
// which will resolve with that username's data.
class Twitter extends Component {
  // finish this
}

This mode decouples the parent component from the child component. The parent component can directly access the internal status of the child component without passing through props, in this way, the parent component can more easily control the UI displayed by the Child component. For example, if the product manager asks us to replace the originally shown badge with the profile, we can easily modify the callback function:

<Twitter username='tylermcginnis33'>
  {(user) => user === null
    ? <Loading />
    : <Profile info={user} />}
</Twitter>
Differences between presentational component and container component
  • Display component care about what the component looks like. The presentation accepts data and callbacks through props, and almost does not have its own status. However, when the display component has its own status, it usually only cares about the UI status rather than the data status.
  • Container components are more concerned about how components work. Container components provide data and behavior (behavior) for the display component or other container components. They call flux actions and provide it as a callback to the display component. Container components are often stateful because they are (other components) data sources.
What is the difference between Class component and functional component?
  • Class components not only allow you to use more additional functions, such as the status and lifecycle hooks of the component, but also allow the component to directly access the store and maintain the status.
  • When a component only receives props and renders itself to a page, it is a 'stateless component )', you can use a pure function to create such a component. Such components are also called dumb components or display components.
What is the difference between the State and props of a component?
  • State is a Data Structure Used as the default value of data required for Component mounting. State may change over time, but most of the time is the result of user event behavior.
  • Props (short for properties) is the configuration of components. Props is passed by the parent component to the child component, and in terms of the child component, props is immutable ). Components cannot change their own props, but they can be put together (managed in a unified manner ). Props is not just data-callback functions can also be passed through props.
What is a controlled component)

In HTML<input>,<textarea>And<select>Such form elements maintain their own States and are updated based on user input. When a user submits a form, the value of the element mentioned above will be sent along with the form. However, there will be some differences in react. components that contain form elements will track the input values in the State, and every time a callback function is called, for example, onchange will update the state and re-render the component. An input form element whose values are controlled by react is called a "Controlled Element ".

Higher Order component)

A high-order component is a function that takes components as parameters and returns a new component. You can use code, logic, and guidance abstraction to run the Hoc program. The most common function is Redux's connect function. In addition to the simple sharing tool library and simple combination, the best way for hoc is to share the behavior between react components. If you find that you write a lot of code in different places to do the same thing, you should consider refactoring the code into reusable hoc.

Why is it recommended that the parameter passed to setstate be a callback rather than an object?

Because updates to this. Props and this. State may be asynchronous and cannot be calculated based on their values for the next state.

Is there any other way to bind this in the constructor?

You can use the property initializers to correctly bind the callback. Create-react-app is also supported by default. You can use the arrow function in the callback, but the problem is that a new callback is created every time the component is rendered.

(In the constructor) What is the purpose of calling super (props )?

Before super () is called, The subclass cannot use this. In es2015, The subclass must call Super () in constructor (). The reason for passing props to super () is that it is convenient (in the subclass) to access this. Props in constructor.

Where should I initiate an Ajax request for the react component?

In the react component, a network request should be sent in componentdidmount. This method is executed when the component is "mounted" for the first time (added to the DOM) and only once in the life cycle of the component. More importantly, you cannot guarantee that the Ajax request has been completed before the component is mounted. If so, you will try to call setstate on an unmounted component, this will not work. Initiating a network request in componentdidmount ensures that this component can be updated.

Describes how an event is handled in react.

To solve cross-browser compatibility problems, the event handler in your react will pass the syntheticevent instance, which is the cross-browser wrapper of the react browser's local event.

These syntheticevents have the same interface as the native events you are used to, except that they are compatible in all browsers. Interestingly, react does not actually attach events to the subnode itself. React listens to all events at the top layer using a single event listener. This is good for performance, which also means that when updating the Dom, react does not need to worry about tracking event listeners.

What is the difference between createelement and cloneelement?

React. createelement (): The jsx syntax uses react. createelement () to construct react elements. It accepts three parameters. The first parameter can be a tag name. Such as Div, span, or react component. The second parameter is the input property. The third and later parameters are used as child components of the component.

React.createElement(
    type,
    [props],
    [...children]
)

React. cloneelement () is similar to react. createelement (). The difference is that the first parameter it passes in is a REACT element, rather than a label name or component. The newly added attribute is incorporated into the original attribute and passed into the returned new element, and the sub-element trophy is replaced.

React.cloneElement(
  element,
  [props],
  [...children]
)
There are three ways to build components in react

React. createclass (), es6 class, and stateless function.

What are the technical components of the react component?
  • Components are usually divided into UI components and container components according to their responsibilities.
  • The UI component is responsible for UI presentation, and the container component is responsible for managing data and logic.
  • The two are linked through the connect method provided by react-Redux.
Brief Introduction to flux ideas

The biggest feature of flux is "one-way data flow ".

  1. User Access View
  2. View sends user action
  3. The dispatcher receives the action and requires the store to update it accordingly.
  4. After the store is updated, a "change" event is issued.
  5. View updates the page after receiving the "change" Event
Scaffolding used in the react Project (this is an open topic)

Creat-react-app yeoman and so on

What about redux?
  • Redux is an application data stream framework that mainly solves the problem of State sharing among components. Its principle is centralized management. It mainly includes three core methods: Action, store, reducer, the workflow is that the view calls the dispatch of the store to receive the action and passes it into the store. The CER performs the state operation. The view obtains the latest data through the getstate provided by the store. flux is also used for data operations, there are four components: Action, dispatch, view, and store. The workflow is that view sends an action, the dispatcher receives the action, and the store updates the data. After the update is complete, the store sends a change, view accepts the change update view. Redux is similar to flux. The main difference is that flux has multiple stores that can change the application status. In flux, dispatcher is used to transmit data to the registration callback event, however, only one updatable store can be defined in Redux. Redux combines store and dispatcher to make the structure simpler and clearer.
  • New state is added, and the State management is clearer. With Redux, the process is more standardized, the amount of manual encoding is reduced, and the encoding efficiency is improved. At the same time, when data is updated, sometimes the component is not required, but it also needs to be re-drawn, which affects the efficiency. Generally, they are used only when building complex projects with multiple interactions and data streams.
What are the disadvantages of redux?
  • The data required by a component must be transmitted by the parent component, but cannot be directly retrieved from the store like in flux.
  • When a component-related data is updated, even if the parent component does not need this component, the parent component will still be render again, which may affect the efficiency, or you need to write complicated shouldcomponentupdate for judgment.

Original article address: 1190000016885832

Summary of common react interview questions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.