Today’s Offer Enroll today and get access to premium content.
App Store Google Play
Beginner

What are the differences between functional and class components in React?

In React, components can be defined as either functional components or class components. Functional components are JavaScript functions that return JSX, while class components are ES6 classes that extend from React.Component.

Here’s a step-by-step breakdown:

  1. Functional Components: Simpler and easier to write. They can accept props and return JSX.
  2. Class Components: More complex and can manage their internal state and lifecycle methods.
  3. Usage: Functional components are often preferred due to their simplicity and the introduction of hooks, which allow them to manage state and side effects.

Example of a functional component:

const Greeting = (props) => { return <h1>Hello, {props.name}!</h1>; };

Example of a class component:

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