This is the 15th day of my participation in Gwen Challenge

Hi, I’m @Luo Zhu, a blogger who keeps writing. Thank you for every like and comment you make.

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.

1. What is a switch component?

A switch component is a component that renders one of many components. We need to use objects to map the props value to the component.

For example, a toggle component can display different pages based on page props.

import HomePage from './HomePage';
import AboutPage from './AboutPage';
import ServicesPage from './ServicesPage';
import ContactPage from './ContactPage';

const PAGES = {
  home: HomePage,
  about: AboutPage,
  services: ServicesPage,
  contact: ContactPage,
};

const Page = props= > {
  const Handler = PAGES[props.page] || ContactPage;

  return <Handler {. props} / >;
};

The keys of the PAGES object can be used in the props type to catch development-time errors.
Page.propTypes = {
  page: PropTypes.oneOf(Object.keys(PAGES)).isRequired,
};
Copy the code

2. Why do we need tosetState()Passing a function?

The reason behind this is that setState() is an asynchronous operation. React batches for state changes for performance reasons, so the state may not change immediately after a call to setState(). This means that you shouldn’t rely on the current state when calling setState(), because you can’t be sure what that state will be. The solution is to pass a function to setState(), taking the previous state as an argument. By doing so, you can avoid the problem of users getting old state values when accessing due to the asynchronous nature of setState().

Suppose the initial count is 0. After three consecutive increment operations, the value will increment by only one.

// Assume this.state.count === 0
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
// this.state.count === 1, not 3
Copy the code

If we pass a function to setState(), the count is incremented correctly.

this.setState((prevState, props) = > ({
  count: prevState.count + props.increment,
}));
// this.state.count === 3
Copy the code

3. WhysetState()Preferred functions over objects in?

React can batch multiple setState() calls into a single update to improve performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values to calculate the next state.

This counter example will not update as expected.

/ / error ❌
this.setState({
  counter: this.state.counter + this.props.increment,
});
Copy the code

The preferred method is to call setState() with a function instead of an object. The function accepts the previous state as the first argument and the props when the update was applied as the second argument.

/ / ✅ correctly
this.setState((prevState, props) = > ({
  counter: prevState.counter + props.increment,
}));
Copy the code

4. What is strict mode in React?

React.StrictMode is a useful component for exposing potential problems in your application. Just like

,

does not render any extra DOM elements. It activates additional checks and warnings for its offspring. These checks apply only to development mode.

import React from 'react';

function ExampleApplication() {
  return (
    <div>
      <Header />
      <React.StrictMode>
        <div>
          <ComponentOne />
          <ComponentTwo />
        </div>
      </React.StrictMode>
      <Footer />
    </div>
  );
}
Copy the code

In the example above, strict mode checking applies only to

and

components.

5. WhyisMounted()Is an anti-pattern, what is the correct solution?

The main use case for isMounted() is to avoid calling setState() after a component has been unmounted because it will issue a warning.

if (this.isMounted()) {
  this.setState({...})
}
Copy the code

Checking isMounted() before calling setState() does eliminate warnings, but it also defeats the purpose of warnings. Using isMounted() is a code smell, because the only reason you’re checking is because you think you might be holding a reference after the component is unmounted.

A best solution is to find where setState() might be called after a component is uninstalled and fix them. This condition is usually caused by a callback, when a component is waiting for some data and is unloaded before the data arrives. Ideally, any callbacks should be cancelled in componentWillUnmount() (before unmounting).

Code smell: In the world of programming, any symptom in Code that can cause a deeper problem is called Code smell. Code smell often reveals deeper problems when doing short feedback iterations of code, which means refactoring code in a small, controlled way.

6. Which pointer events are supported in React?

Pointer events provide a unified way to handle all input events. In the past, we had a mouse and separate event listeners to handle them, but now we have many devices that are not associated with having a mouse, such as phones or pens with touch surfaces. We need to remember that these Events only work in browsers that support the Pointer Events specification.

The following event types are now available in the React DOM.

  1. onPointerDown
  2. onPointerMove
  3. onPointerUp
  4. onPointerCancel
  5. onGotPointerCapture
  6. onLostPointerCapture
  7. onPointerEnter
  8. onPointerLeave
  9. onPointerOver
  10. onPointerOut

7. Why do component names start with a capital letter?

If you render your component using JSX, the name of the component must begin with a capital letter, otherwise React will throw an error with an unrecognized label. This convention is because only HTML elements and SVG tags can start with a lowercase letter.

class SomeComponent extends Component {
  // The code will not stop
}
Copy the code

You can define a component class whose name starts with a lowercase letter, but when it is imported, it should be uppercase. In this case, lower case will do.

class myComponent extends Component {
  render() {
    return <div />; }}export default myComponent;
Copy the code

When importing another file, it should start with a capital letter.

import MyComponent from './MyComponent';
Copy the code

What are the exceptions to naming the React component?

Component names should start with a capital letter, but there are a few exceptions to this convention. Dotted lower-case tag names (property accessors) are still considered valid component names.

For example, the following tag can be compiled into a valid component.

render(){
return (
    <obj.component /> // `React.createElement(obj.component)`)}Copy the code

8. Does React V16 support custom DOM attributes?

Yes, in the past React used to ignore unknown DOM attributes. If you write JSX with a property React doesn’t recognize, React will skip it.

For example, let’s look at the following properties.

<div mycustomattribute={'something'} / >Copy the code

React V15 renders an empty div onto the DOM.

<div />
Copy the code

In React V16, any unknown properties end up in the DOM.

<div mycustomattribute="something" />
Copy the code

This is useful for providing browser-specific non-standard properties, trying out new DOM apis, and integrating with independent-minded third-party libraries.

9. What is the difference between constructor and getInitialState?

When using ES6 classes, you should initialize the state in the constructor, and when using React. CreateClass (), you should initialize the state in the getInitialState() method.

Using ES6 classes:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      /* Initialization state */}; }}Copy the code

useReact.createClass():

const MyComponent = React.createClass({
  getInitialState() {
    return {
      /* Initialization state */}; }});Copy the code

Note: React. CreateClass () was deprecated and removed in React V16. Use a normal JavaScript class instead.

10. Can you force a component to rerender without calling setState?

By default, your component is re-rendered when the state or props of your component changes. If your render() method depends on other data, you can tell React that the component needs to be rerendered by calling forceUpdate().

component.forceUpdate(callback);
Copy the code

It is recommended to avoid forceUpdate() and just read this.props and this.state in Render ().