Sobes.tech
Middle+

What are class-based and functional components in React? How do they differ?

sobes.tech AI

Answer from AI

In React, there are two main types of components: class components and functional components.

Class components are components defined as classes that extend React.Component. They can have state and lifecycle methods.

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

  componentDidMount() {
    // code after mounting
  }

  render() {
    return <div>{this.state.count}</div>;
  }
}

Functional components are functions that accept props and return JSX. They were previously "static" and did not have state or lifecycle methods, but with the introduction of hooks, functional components can now use state and other React features.

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

  React.useEffect(() => {
    // code after mounting
  }, []);

  return <div>{count}</div>;
}

Differences:

  • Class components use this, functional components do not.
  • Functional components with hooks are more concise and easier to understand.
  • Modern React recommends using functional components with hooks as they are more flexible and allow better code optimization.
What are class-based and functional components in… - sobes.tech