Hi, I’m @Luo Zhu

This article was first published on luo Zhu’s official website

Translated from Sudheerj/reactJs-interlocution-Questions

This article synchronizes in the public account Luo Zhu early teahouse, reprint please contact the author.

  • React Interview Questions series Day1
  • React Interview Questions series Day2
  • React Interview Questions series Day3

1. What is the difference between createElement and cloneElement?

The JSX elements will be converted to the react.createElement () function to create React elements, which will be used for the object representation of the UI. The cloneElement is used to clone the element and pass the new props to it.

After class extension:

  • The React the top API

2. What are state boosts in React?

When multiple components need to share the same changing data, it is recommended that the shared state be promoted to their nearest common ancestor. This means that if two child components share the same data from their parent, the state is moved to the parent instead of maintaining internal state in both child components.

3. What are the different phases of the component life cycle?

The component lifecycle has three distinct lifecycle phases.

  1. Mounting:The component is ready to install in the browser DOM. This phase covers the lifecycle approachconstructor(),getDerivedStateFromProps(),render()componentDidMount()Initialization of.
  2. Updating:At this stage, components are updated in two ways, sending newpropsAnd from thesetState()forceUpdate()Update status. This phase coversgetDerivedStateFromProps().shouldComponentUpdate().render()getSnapshotBeforeUpdate()componentDidUpdate()Lifecycle methods.
  3. Unmounting:In the final stage, the component is no longer needed and is uninstalled from the browser DOM. This phase includescomponentWillUnmount()Lifecycle methods.

It’s worth noting that React has a phased concept inside when applying changes to the DOM. They are separated as follows

  1. Render: This component will Render without any side effects. This applies to Pure components, where React can pause, halt, or restart rendering.
  2. The Pre – commit:React is allowed to pass for a while before the component actually applies the changes to the DOMgetSnapshotBeforeUpdate()Read content from the DOM.
  3. Commit:React works with DOM and executes the final lifecycle separately:componentDidMount()For installation,componentDidUpdate()For updates, as wellcomponentWillUnmount()Used for uninstallation.

React 16.3+ (or online Interactive version)

React 16.3 earlier versions:

4. What are the React life cycles?

React 16.3 Earlier versions:

  • ComponentWillMount: Executed before rendering for application-level configuration in the root component.
  • ComponentDidMount: Executed after the first rendering, where all AJAX requests, DOM or status updates, and setup event listeners should be executed.
  • Update componentWillReceiveProps: in a particular attribute to trigger a state transition.
  • ShouldComponentUpdate:Determines whether to update the component. By default, it returnstrue. Return if you determine that you do not need to render the component after a state or property updatefalseValue. This is a good place to improve performance if the component receives a new oneprops, which prevents re-rendering.
  • ComponentWillUpdate:When a property or state changes byshouldComponentUpdate()Confirm and returntrueIs executed before the component is rerendered.
  • ComponentDidUpdate: Typically, it is used to update the DOM in response to property or state changes.
  • ComponentWillUnmount: This will be used to cancel any outgoing network requests or remove any event listeners associated with this component.

The React version 16.3 +

  • GetDerivedStateFromProps:In the callrender()Is called before, and will be called on every render. This exists for rare use cases that require derived state.If you need to derive stateIt’s worth reading.
  • ComponentDidMount: Executes after the first rendering, and all AJAX requests, DOM or status updates, and setup event listeners should occur here.
  • ShouldComponentUpdate:Determines whether the component will be updated. By default, it returnstrue. Return if you determine that you do not need to render the component after a state or property updatefalseValue. This is a good place to improve performance, because it prevents re-rendering if the component receives new properties.
  • GetSnapshotBeforeUpdate:Execute immediately before rendering the output to the DOM. Any value returned by this method is passed tocomponentDidUpdate()In the. This is useful for capturing information from the DOM, the scrolling position.
  • ComponentDidUpdate:Typically, it is used to update the DOM in response to property or state changes. ifshouldComponentUpdate()returnfalseIs not triggered.
  • ComponentWillUnmount: This will be used to cancel any outgoing network requests or remove any event listeners associated with this component.

5. What are the higher-order components

HOC is a function that receives a component and returns a new component. Basically, this is a pattern derived from the constituent properties of React.

We call them pure components because they can accept any dynamically supplied child component, but they do not modify or copy any behavior in their input component.

const EnhancedComponent = higherOrderComponent(WrappedComponent)
Copy the code

HOC can be used in many scenarios:

  1. Code reuse, logic, and bootstrap abstraction.
  2. Render hijacking.
  3. State abstraction and manipulation.
  4. Props.

6. How to create props agent for HOC component?

You can use the property proxy mode to add or edit properties passed to the component, as follows:

function HOC(WrappedComponent) {
  return class Test extends Component {
    render() {
      const newProps = {
        title: 'New Header'.footer: false.showFeatureX: false.showFeatureY: true
      }

      return <WrappedComponent {. this.props} {. newProps} / >}}}Copy the code

After class extension:

  • React Proxy mode for high-level components

7. What is context?

Context provides a way to pass data through a tree of components without having to manually pass properties layer by layer.

For example, many components need to access authenticated users in the application, set preferences locally, UI themes, and so on.

const {Provider, Consumer} = React.createContext(defaultValue)
Copy the code

8. What is the Children attribute?

Children is a prop (this.props. Children) that allows you to pass components as data to other components, just like any other prop you use. The component tree placed between the component’s start tag and end tag is passed to the component as a Children item.

The React API has a number of methods available for this property. These include react.children. map, react.children. forEach, react.children. count, react.children. only, and react.children.toarray.

The simple use of children is as follows:

const MyDiv = React.createClass({
  render: function() {
    return <div>{this.props.children}</div>
  }
})

ReactDOM.render(
  <MyDiv>
    <span>{'Hello'}</span>
    <span>{'World'}</span>
  </MyDiv>,
  node
)
Copy the code

9. How to write comments in React?

Comments in React JSX are similar to JavaScript multi-line comments, but enclosed in braces.

One-line comment:

<div>
  {/* This is a single line comment */}
  {`Welcome ${user}, let's play React`}
</div>
Copy the code

Multi-line comments:

<div>
  {/* Multi-line comments for more than one line */}
  {`Welcome ${user}, let's play React`}
</div>
Copy the code

10. Give from constructorsuperWhat is the purpose of the function passing props?

A subclass constructor cannot get the this reference until the super() method is called. The same goes for sub-classes in ES6. The main reason to pass props when calling super() is to access this.props in the constructor of the subclass.

Pass props:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)

    console.log(this.props) // Print {name: 'John', age: 42}}}Copy the code

Don’t pass props:

class MyComponent extends React.Component {
  constructor(props) {
    super(a)console.log(this.props) / / print undefined

    // But the props parameter is still accessible
    console.log(props) // Print {name: 'John', age: 42}
  }

  render() {
    // No effect outside of constructor
    console.log(this.props) // Print {name: 'John', age: 42}}}Copy the code

The code snippet above reveals that this.props differs only in the constructor. Outside the constructor, the appearance will be the same.

For more information why do we want to say super(props)?