List of most commonly asked React Interview Questions.

Differences between Class and Functional Components in React.

Explain the differences between Class and Functional Components in React.

Functional components and class components are two different ways of creating components in React. Here's a breakdown of the key differences between them:

Functional Components:

  • Functional components are written as JavaScript functions.

  • They are also known as stateless or presentational components because they don't have their own internal state.

  • Functional components are simpler and easier to read and write compared to class components.

  • They are typically used for rendering UI elements based on the props passed to them.

  • Functional components are mainly concerned with the output they render based on the input received through props.

Example of a functional component:

const FunctionalComponent = (props) => {
  return <div>{props.message}</div>;
};

Class Components:

  • Class components are written as ES6 classes that extend the React.Component class provided by React.

  • They are also known as stateful components because they can have their own internal state using the state property.

  • Class components have more features and capabilities, such as lifecycle methods and the ability to manage state.

  • They are typically used for components that require complex logic, state management, or interactions with the component lifecycle.

Example of a class component:

class ClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

Note that with the introduction of React hooks, such as the useState hook, functional components can now have their own state and manage lifecycle-related actions. This blurs the distinction between functional and class components to some extent, but the fundamental difference still lies in the syntax and usage patterns.

In recent years, functional components have gained popularity due to their simplicity and the availability of hooks, which provide similar capabilities as class components. However, both functional and class components are still used in React applications, and the choice between them depends on the specific requirements of the component and the developer's preference or project conventions.