React classic interview questions with detailed answers (August 23)

  1. What are the component lifecycles in React?
    Answer: The component life cycle in React includes a mount phase, an update phase, and an unmount phase. The specific life cycle methods are:
  • Mount phase: constructor, render, componentDidMount
  • Update phase: render, componentDidUpdate
  • Unmount phase: componentWillUnmount
  1. Is setState in React synchronous or asynchronous?
    Answer: The setState method is asynchronous. React will combine multiple setState calls into a single call to improve performance. If you need to get the updated state immediately after setState, you can use the callback function as the second parameter of setState.

  2. What is the difference between controlled and uncontrolled components in React?
    Answer: A controlled component is a component whose state is controlled by React, receiving and updating data through props. Uncontrolled components are components that control the state of the DOM itself, and obtain and update data through ref.

  3. What does the key attribute in React do?
    Answer: The key attribute is used to help React identify the uniqueness of each element in the list to improve performance. When the list is updated, React uses the key to determine which elements were added, removed, or modified.

  4. What are the ways of event handling in React?
    Answer: Event handling in React can be done in the following ways:

  • Use event processing functions directly in JSX, such as onClick, onChange, etc.
  • Use event listeners such as addEventListener.
  • Use a third-party library, such as the Link component provided by React Router.
  1. What are the ways of conditional rendering in React?
    Answer: Conditional rendering in React can be done in the following ways:
  • Use if statements or ternary expressions to perform conditional judgments in the render method.
  • Use the && operator for conditional rendering.
  • Use the switch statement for multiple conditional rendering.
  1. How to handle form input in React?
    Answer: React can handle form input through the onChange event. Get the value of the input through the event handler and save it to the component's state.

Sample code:

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    };
  }

  handleChange(event) {
    this.setState({ inputValue: event.target.value });
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log('Input value:', this.state.inputValue);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit.bind(this)}>
        <input type="text" value={this.state.inputValue} onChange={this.handleChange.bind(this)} />
        <button type="submit">Submit</button>
      </form>
    );
  }
}
  1. What is Context in React?
    Answer: Context is a mechanism provided by React to pass data across components. It can avoid passing data layer by layer through props, making data sharing between components more convenient.

Sample code:

const MyContext = React.createContext();

class ParentComponent extends React.Component {
  render() {
    return (
      <MyContext.Provider value="Hello from ParentComponent">
        <ChildComponent />
      </MyContext.Provider>
    );
  }
}

class ChildComponent extends React.Component {
  render() {
    return (
      <MyContext.Consumer>
        {value => <div>{value}</div>}
      </MyContext.Consumer>
    );
  }
}
  1. How to communicate between components in React?
    Answer: React can communicate between components through props, context and events. Props are used for communication between parent and child components, Context is used to pass data across components, and events are used for communication between child components and parent components.

  2. What is virtual DOM in React?
    Answer: The virtual DOM is an in-memory representation in React that is a lightweight abstraction of the real DOM. React uses virtual DOM to improve rendering performance, and minimizes the operation of real DOM by comparing the differences of virtual DOM.

  3. What are Fragments in React?
    Answer: Fragment is a component provided by React, which is used to group and return multiple sub-elements without adding additional nodes. It can help reduce unnecessary DOM nesting.

Sample code:

class MyComponent extends React.Component {
  render() {
    return (
      <React.Fragment>
        <div>Child 1</div>
        <div>Child 2</div>
        <div>Child 3</div>
      </React.Fragment>
    );
  }
}
  1. What are error boundaries in React?
    A: An error boundary is a React component that catches and handles JavaScript errors in its child components. It prevents error propagation and provides elegant error handling.

Sample code:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.error(error);
  }

  render() {
    if (this.state.hasError) {
      return <div>Oops, something went wrong.</div>;
    }
    return this.props.children;
  }
}

class MyComponent extends React.Component {
  render() {
    if (this.props.shouldThrowError) {
      throw new Error('Error occurred.');
    }
    return <div>No error occurred.</div>;
  }
}

class App extends React.Component {
  render() {
    return (
      <ErrorBoundary>
        <MyComponent shouldThrowError={true} />
      </ErrorBoundary>
    );
  }
}
  1. What is a Higher Order Component (HOC) in React?
    Answer: Higher-order components are a pattern for reusing component logic. It is a function that takes a component as an argument and returns a new component.

Sample code:

function withLogging(WrappedComponent) {
  return class extends React.Component {
    componentDidMount() {
      console.log('Component is mounted.');
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
}

class MyComponent extends React.Component {
  render() {
    return <div>Hello, World!</div>;
  }
}

const EnhancedComponent = withLogging(MyComponent);
  1. What are the performance optimizations in React?
    Answer: The performance optimization of React can be achieved in the following ways:
  • Use PureComponent or shouldComponentUpdate methods to avoid unnecessary rendering.
  • Use memo functions to optimize the rendering of function components.
  • Use React's code splitting and lazy loading to reduce initial load time.
  • Use React's virtual lists or infinite scrolling to handle the rendering of large amounts of data.
  • Use React's server-side rendering (SSR) to improve first-load speed and SEO friendliness.
  1. What are Hooks in React?
    Answer: Hooks is a new feature introduced by React 16.8, which allows function components to have the functionality of class components. By using Hooks, you can use state, lifecycle, and other React features without writing class components.

Sample code:

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
  1. What is Code Splitting in React?
    A: React's code splitting is a technique for splitting application code into smaller chunks. It can help reduce the initial load time and improve the performance of the application.

Sample code:

import React, { lazy, Suspense } from 'react';

const MyComponent = lazy(() => import('./MyComponent'));

function App() {
  return (
    <div>
           <Suspense fallback={<div>Loading...</div>}>
        <MyComponent />
      </Suspense>
    </div>
  );
}

In the above example, the MyComponent component is code-split using the lazy function. In the App component, use the Suspense component to provide a load-time placeholder and asynchronously load the MyComponent component when needed.

  1. What is context in React?
    A: Contexts are a mechanism in React for sharing data across component hierarchies. It avoids the tedious process of explicitly passing props through the component tree.

Sample code:

const MyContext = React.createContext();

function MyComponent() {
  return (
    <MyContext.Consumer>
      {value => <div>Value from context: {value}</div>}
    </MyContext.Consumer>
  );
}

function App() {
  return (
    <MyContext.Provider value="Hello, World!">
      <MyComponent />
    </MyContext.Provider>
  );
}

In the above example, a context object MyContext is created using the createContext function. In the App component, use the MyContext.Provider component to pass the value to the MyComponent component. In the MyComponent component, use the MyContext.Consumer component to get the context value and render it.

  1. What is the render property pattern in React?
    Answer: Rendering property mode is a mode that realizes component reuse by using functions as properties of components. It can help reduce duplicated code and increase the flexibility of components.

Sample code:

function MyComponent({ render }) {
  return <div>{render('Hello, World!')}</div>;
}

function App() {
  return (
    <MyComponent
      render={value => (
        <div>Value from render prop: {value}</div>
      )}
    />
  );
}

In the above example, the MyComponent component receives a function through the render attribute, and renders the return value of the function as content. In the App component, pass a function through the render attribute to define what to render.

  1. What is the difference between controlled and uncontrolled components in React?
    Answer: Controlled components are components that React controls the value and state of form elements. It implements two-way data binding by using value or checked attribute and onChange event handler.

Uncontrolled components are components in which the value and state of form elements are controlled by the DOM itself. It uses ref to get the value of the form element and does not need to use value or checked attribute and onChange event handler.

Sample code:

// 受控组件
class ControlledComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  render() {
    return (
      <input
        type="text"
        value={this.state.value}
        onChange={event => this.handleChange(event)}
      />
    );
  }
}

// 非受控组件
class UncontrolledComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log('Input value:', this.inputRef.current.value);
  }

  render() {
    return (
      <form onSubmit={event => this.handleSubmit(event)}>
        <input type="text" ref={this.inputRef} />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

In the above example, ControlledComponent is a controlled component that controls the value of the input box through the value property and the onChange event handler. UncontrolledComponent is an uncontrolled component that uses ref to get the value of the input box, and does not use the value attribute and onChange event handler.

  1. What are error boundaries in React?
    A: An error boundary is a React component that catches and handles JavaScript errors in its child components. It prevents error propagation and provides elegant error handling.

Sample code:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.error(error);
  }

  render() {
    if (this.state.hasError) {
      return <div>Oops, something went wrong.</div>;
    }
    return this.props.children;
  }
}

class MyComponent extends React.Component {
  render() {
    if (this.props.shouldThrowError) {
      throw new Error('Error occurred.');
    }
    return <div>No error occurred.</div>;
  }
}

class App extends React.Component {
  render() {
    return (
      <ErrorBoundary>
        <MyComponent shouldThrowError={true} />
      </ErrorBoundary>
    );
  }
}

In the above example, the ErrorBoundary component catches and handles errors in the MyComponent component. If the MyComponent component throws an error, the ErrorBoundary component will render an error message, otherwise it will render the content of the MyComponent component.

Guess you like

Origin blog.csdn.net/ACCPluzhiqi/article/details/132462055