preface

This article is long, all dry goods, it is suggested that relatives can first collect slowly look at oh

Writing is not easy, welcome to communicate with you, like the article remember to pay attention to me a thumb-up yo, thank you for your support!

Q1: What is the virtual DOM?

Difficulty: : star:

The virtual DOM (VDOM) is an in-memory representation of the real DOM, a programming concept, and a pattern. It synchronizes with the real DOM, for example through libraries like ReactDOM, in a process called reconcilation.

The virtual DOM is more of a pattern than a specific technology.

:link: Source: github.com/sudheerj

Resources: What is the virtual DOM

Q2: What’s the difference between a class component and a function component?

Difficulty: : star: : star:

  • Class Components

  • Whether a component is declared using functions or classes, it must never modify its own props.

  • All React components must be pure functions and do not modify their own props.

  • React is a single data stream. If the parent component changes its properties, the child component view is updated.

  • The props property is passed from the outside, and the state is the component itself. The state can be modified in the component at will

  • Component properties and state changes update the view.

    class Welcome extends React.Component { render() { return (

    Welcome { this.props.name }

    ); } } ReactDOM.render(, document.getElementById(‘root’));

  • Functional Component

  • The function component takes a single props object and returns a React element

function Welcome (props) { return

Welcome {props.name}

The difference between

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.

Function component class component whether this does not have whether it has a life cycle does not have whether it has stateful State Does not have

:link: Source: github.com/Pau1fitz

: Link: Resources: Function components differ from class components

Q3: What does refs do in React?

Difficulty: : star: : star:

Refs is a handle to a DOM element or component instance that React provides us with secure access.

We can add the ref attribute to the element and then accept the element’s handle to the DOM tree in the callback function, which is returned as the first argument to the callback function:

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

The input field in the code above contains a ref attribute that declares a callback function that accepts the DOM element corresponding to the input, which we bind to the this pointer for use in other class functions.

It is also worth noting that refs are not exclusive to class components. Functional components can also use closures to temporarily store their values:

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

:link: Source: github.com/Pau1fitz

: Link: Resources: stackoverflow.com/que…

Q4: Describes React event processing.

Difficulty: : star: : star:

To address cross-browser compatibility issues, the Event handler in React passes SyntheticEvent instances, which are cross-browser wrappers for React cross-browser native events. These composite events have the same interface as your usual native events, except that they work the same way in all browsers.

Somewhat interestingly, React doesn’t actually attach the event to the child node itself. React will use a single event listener at the top level to listen for all events. This is good for performance and means React doesn’t have to worry about tracking event listeners when updating the DOM.

: Link: Source: tylermcginnis.com

: Link: Resources: www.cnblogs.com/xiang…

Q5: What is the difference between props and state?

Difficulty: : star: : star:

Both state and props are plain JavaScript objects. Although they both have information that affects the rendered output, they differ in their component-wise functionality. namely

  • propsIs a parameter that is passed to a component from outside. It is used to pass data from a parent component to a child component. It is readable and immutablepropsTo re-render the child component, otherwise the child component’spropsAnd the presentation will not change.
  • stateIs used by components to save, control, and modify their stateconstructorIt is a private property of the component and cannot be accessed or modified externally, only internallythis.setStateTo modify, modifystateProperty causes the component to be rerendered.

:link: Source: HTTPS: //github.com/sudheerj

: Link: Resources: stackoverflow.com/que…

Q6: How do I create refs?

Difficulty: : star: : star:

Refs are created using the React.createref () method and added to the React element via the ref attribute. To use refs throughout the component, you simply assign the ref to the instance property in the constructor

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

And:

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

We can also use it in feature components with closures.

:link: Source: github.com/sudheerj

: Link: Resources: segmentfault.com/a/11…

Q7: What are higher-order components?

Difficulty: : star: : star:

A higher-order component is a function that takes a component as an argument and returns a new component. Basically, this is a pattern derived from the constituent nature of React, and we call them “pure” components because they can accept any dynamically supplied subcomponents, but they don’t modify or copy any behavior of their input components.

const EnhancedComponent = higherOrderComponent(WrappedComponent);
Copy the code
  • HOC is an advanced technique used in React to reuse component logic
  • The higher-order component argument returns a new component for a component
  • A component converts props to UI, and a higher-order component converts a component to another component

:link: Source: github.com/sudheerj

: Link: Resources: css-tricks.com/what-a…

Q8: What is the purpose of using super with props in constructor?

Difficulty: : star: : star:

The subclass constructor cannot use this to reference super() until the method is called.

In ES6, you must first call super in the constructor subclass to refer to this.

You can use this. Props in constructor

The use of props:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props);  // Prints { name: 'sudheer',age: 30 }
    }
}
Copy the code

Without using props:

class MyComponent extends React.Component {
    constructor(props) {
        super();
        console.log(this.props); // Prints undefined
        // But Props parameter is still available
        console.log(props); // Prints { name: 'sudheer',age: 30 }
    }

    render() {
        // No difference outside constructor
        console.log(this.props) // Prints { name: 'sudheer',age: 30 }
    }
}
Copy the code

The code snippet above reveals that the behavior of this.props differs only in the constructor. The external constructor is the same.

: Link: Source: github.com/sudheerj www.fullstack.cafe/Re…

Q9: What is a controlled component?

Difficulty: : star: : star: : star:

In HTML, form elements like ,

Uncontrolled component

An uncontrolled component is a component whose state is not controlled by React, such as the one below

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Demo1 extends Component {
    render() {
        return (
            <input />
        )
    }
}

ReactDOM.render(<Demo1/>, document.getElementById('content'))
Copy the code

In the simplest input box component, we do not interfere with the value display in the input, meaning that user input is displayed there. If we set an initial defaultValue to the component via props, the defaultValue property is a property implemented inside React, with the same purpose as the input placeholder property.

The controlled components

Similarly, a controlled component is a component whose state is controlled by React. As mentioned above, since we cannot change the value of the input field by setting the value property of the input field, we can combine it with state and bind the onChange event to update the value in real time.

class Demo1 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: props.value
        }
    }

    handleChange(e) {
        this.setState({
            value: e.target.value
        })
    }

    render() {
        return (
            <input value={this.state.value} onChange={e => this.handleChange(e)}/>
        )
    }
}
Copy the code

:link: Source: github.com/Pau1fitz

: Link: Resources: www.php.cn/js-tutoria….

Q10: What is the following equivalent using React. CreateElement?

Difficulty: : star: : star: : star:

Question:

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);
Copy the code

What is the following equivalent to using React. CreateElement?

A:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);
Copy the code

:link: Source: github.com/Pau1fitz

Q11: What is JSX?

Difficulty: : star: : star: : star:

JSX stands for JavaScript XML. An XML-like syntax for building tags inside the React component. JSX developed a set of syntactic candy for react.js, which is the basis for the use of react.js. React works without JSX, however it is recommended to use JSX because it improves the readability of components.

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

Advantages:

1. Allow familiar syntax to define HTML element trees;

2. Provide more semantic and mobile labels;

3. The program structure is easier to be visualized;

React Element creation process abstract;

5. You can control HTML tags and the code that generates them at any time;

6. Native JavaScript.

: Link: Source: codementor. IO

: Link: Resources: facebook.github. IO/JSX /

Q12: Why not update state state directly?

Difficulty: : star: : star: : star:

If the state is updated as follows, it will not re-render the component.

/ / Wrong This. State. The message = "Hello world";Copy the code

Instead, use the setState() method. It plans updates to component state objects. When the state changes, the component responds by re-rendering

/ / Correct This. SetState ({message: "Hello World"});Copy the code

Note: The only place you can assign state is the constructor.

:link: Source: HTTPS: //github.com/sudheerj

Q13: What are the different phases of the ReactJS life cycle?

Difficulty: : star: : star: : star:

The React component lifecycle is divided into four distinct phases:

  1. Initialization: In this phase, the React component is ready to set the initial state and default items.

  2. Mount: The React component is ready to mount in the browser DOM. This phase covers the componentWillMount and componentDidMount lifecycle methods.

  3. Update: In this phase, components are updated in two ways, by sending new items and updating their status. This phase covers shouldComponentUpdate, componentWillUpdate, and componentDidUpdate lifecycle methods.

  4. Uninstall: In the final stage, this component is not needed and can be uninstalled from the browser DOM. This phase includes the componentWillUnmount lifecycle method.

:link: Source: github.com/sudheerj

Q14: What is the lifecycle method of ReactJS?

Difficulty: : star: : star: : star:

  • ComponentWillMount: Executed before rendering for application-level configuration in the root component.
  • ComponentDidMount:It is executed only after the client’s first rendering. This is where AJAX requests and DOM or status updates should occur. This method is also used with other JavaScript frameworks and any functions that are delayed in execution (e.gsetTimeoutsetInterval), which is used here to update state so that we can trigger other lifecycle methods.
  • ComponentWillReceiveProps:Just update before another render is calledpropsIs called. When we update the status fromsetNewNumberTrigger it.
  • ShouldComponentUpdate: Determines whether the component will be updated. By default, it returns true. Return false if you determine that the component does not need to render after a status or item update. This is a good place to improve performance, as it prevents re-rendering if the component receives a new item.
  • ComponentWillUpdate: Executed before rerendering the component when the benefit of returning positive values and status changes are confirmed by shouldComponentUpdate.
  • ComponentDidUpdate: Typically 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.

: Link: Source: github.com/sudheerj www.fullstack.cafe/Re…

Q15: React these three points (…) What do you do?

Difficulty: : star: : star: : star:

. What do I do in this React code? What is it called?

<Modal {... this.props} title='Modal heading' animation={false}>Copy the code

Extended transfer symbol. It was added in ES2018 (arrays/iterables were propagated earlier, ES2015).

For example, if this.props contains a: 1 and b: 2, then

<Modal {... this.props} title='Modal heading' animation={false}>Copy the code

The same as the following:

<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
Copy the code

Not only does the extension notation work for this use case, it’s also handy for creating new objects with most (or all) of the properties of existing objects – there are a lot of problems when updating the state, because you can’t change the state straight:

this.setState(prevState => { return {foo: {... prevState.foo, a: "updated"}}; });Copy the code

: Link: Source: stackOverflow.com

Q16: What are the advantages of using React Hooks?

Difficulty: : star: : star: : star:

Hooks are a feature introduced in React 16.8 that allows you to manipulate state and other react features without writing classes.

Hooks simply add a way to write components, making it easier and more convenient to write a component. They also allow custom hooks to extract common logic and share logic between components.

What is the Hook

What is a Hook? Hook is a special function that lets you “Hook” into the React feature. For example, useState is a Hook that allows you to add state to the React function component. We’ll look at other hooks later.

When can I Hook? If you were writing a function component and realized you needed to add some state to it, the old practice was that you had to convert the rest to class. You can now use hooks in existing function components.

The advantages of ReactHooks

  • No complex DOM structure is required
  • Concise and easy to understand

: Link: Source: hackernoon.com

Q17: useState in React?

Difficulty: : star: : star: : star:

Case study:

import { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  )
}
Copy the code

Grammar:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
Copy the code

Where state is its value, setState is the function used to set the value, and initialState is the initial value

useState-initialState

This initialization can take any parameter, but remember that when it is accepted as a function, it becomes Lazy initialization.

The return value of this function is initialState

const [count, setCount] = useState(0); const [count, setCount] = useState(()=>0); Const [count, const [count, const [count, const [count, SetCount] = useState(()=>{console.log(' this is only done on initialization ') // Return 0}); // When executed for the first time, it is the same as the other line of codeCopy the code

useState-setState

A lot of people probably use the callback function when they use the setState of a class,

Unfortunately, it only accepts new values. If you want the corresponding callback, you can use useEffect. This question will provide a jump link later

Q18: What is StrictMode in React?

Difficulty: : star: : star: : star:

StrictMode is a helper component that helps you write better React components. You can use a wrapper to wrap some components,
and basically:

  • Verify that internal components follow certain recommended practices and issue warnings if they are not in the console.
  • Validates methods that are deprecated and warns you in the console if strict mode is used.
  • Help you prevent certain side effects by identifying potential risks.

: link: resources: the react. HTML. Cn/docs/STR…

Q19: Why do class methods need bindings?

Difficulty: : star: : star: : star:

In JavaScript, the value of this depends on the current context. In component methods of the React class, developers usually want it to refer to the current instance of the component, so it’s necessary to bind these methods to that instance. Typically, this is done in constructors, such as:

class SubmitButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFormSubmitted: false
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit() {
    this.setState({
      isFormSubmitted: true
    });
  }

  render() {
    return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
  }
}
Copy the code

: Link: Source: toptal.com

Q20: Describe Flux and MVC?

Difficulty: : star: : star: : star: : star:

The traditional MVC pattern works well in separating the concerns of data (model), UI (view), and logic (controller), but the MVC architecture often runs into two main problems:

  • Poorly defined data flows: Cascading updates across views often result in a tangled web of events that are difficult to debug.
  • Lack of data integrity: Model data can be mutated from anywhere, resulting in unpredictable results across the ENTIRE UI.

With Flux mode, complex UIs are no longer plagued by cascading updates. Any given React component will be able to reconstruct its state based on the data provided by the store. The Flux pattern also enhances data integrity by limiting direct access to shared data.

: Link: Source: codementor. IO www.fullstack.cafe/Re…

Q21: React Context?

Difficulty: : star: : star: : star: : star:

The React document website does not define a Context. It describes the Context used and how to use it.

The official website describes the Context scenario as follows:

In Some Cases, you want to pass data through the component tree without having to pass the props down manuallys at every level. you can do this directly in React with the powerful “context” API.

Simply put, when you don’t want to pass props or state layer by layer in the component tree, you can use Context to pass component data across layers.

Pass data using props or state, and the data flows from the top.

Using Context, you can pass data across components.

:link: Source: github.com/WebPredict

Q22: What is React Fiber?

Difficulty: : star: : star: : star: : star:

React Fiber is not a so-called Fiber (microthreading, coroutine), but a browser-based single-threaded scheduling algorithm backed by a well-known API: requestIdleCallback.

Fiberl is an algorithm that breaks recocilation, or recursive diff, into countless small tasks; It can stop and resume at any time. The timing of stopping recovery depends on whether there is enough time in the current frame (16ms) to allow calculation.