Câu hỏi phỏng vấn Reactjs
Câu hỏi

What are the differences between a Class component and Functional component?

Câu trả lời

In React, the differences between Class components and Functional components are primarily based on their syntax, lifecycle methods, state management, and modern usage trends. Here’s a detailed comparison:

Syntax and Declaration

  • Functional Components: These are simpler and declared as JavaScript functions. They directly return JSX and are typically used for components that do not require state or lifecycle methods. A functional component accepts props as an argument and returns a React element[1][2][5].

    Example:

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
  • Class Components: These are more complex and are declared as classes extending React.Component. They must include a render() method that returns JSX. Class components are suitable for more complex scenarios where state management and lifecycle methods are needed[1][2][5].

    Example:

    class Welcome extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }

State Management

  • Functional Components: Initially, they did not support state or lifecycle features. However, with the introduction of Hooks in React 16.8, functional components can now use state and other features like side effects through the useState and useEffect hooks[1][2][6].

  • Class Components: They have built-in state management capabilities. State is typically initialized in the constructor and modified using this.setState(). They provide a more structured approach to handling state, especially in complex scenarios[1][2].

Lifecycle Methods

  • Functional Components: Before hooks, functional components did not have access to lifecycle methods. Hooks like useEffect allow functional components to perform side effects, which can be used to replicate lifecycle behaviors[1][2][6].

  • Class Components: They provide several lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount for handling operations before and after rendering or when component updates are necessary[1][2].

Use Cases

  • Functional Components: Recommended for most new comp...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

Explain the Virtual DOM concept in React

junior

What are inline conditional expressions in ReactJS?

junior

What are refs used for in React?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào