13 Feb 2024




Beginner

Functional Components:

Functional components are the simplest form of React components. They are basically JavaScript functions that take props (properties) as arguments and return React elements to describe what should appear on the screen. Functional components are preferred when you don't need to use state or lifecycle methods.

Example of a functional component:

import React from 'react';

const FunctionalComponent = (props) => {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>This is a functional component.</p>
    </div>
  );
};

export default FunctionalComponent;

Explanation:

  • We define a function named FunctionalComponent that takes props as its argument.
  • Inside the function, we return a JSX element, which describes the structure of the component.
  • We can access props using the props object (e.g., props.name).
  • Finally, we export the component so that it can be imported and used in other parts of the application.

Class Components:

Class components are JavaScript classes that extend from React.Component. They are used when you need to manage state or use lifecycle methods.

Example of a class component:

import React, { Component } from 'react';

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

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

export default ClassComponent;

Explanation:

  • We define a class named ClassComponent that extends React.Component.
  • Inside the class, we define a constructor where we initialize the component's state. State is initialized using this.state.
  • The render() method is mandatory in class components. It returns the JSX element that describes what should be rendered on the screen.
  • In this example, we have a button that increments the count when clicked. We update the state using this.setState() method, which triggers a re-render of the component.
  • Finally, we export the component so that it can be imported and used in other parts of the application.

In summary, functional components are simpler and used when you don't need state or lifecycle methods, while class components are used when you need state or lifecycle methods. However, with the introduction of React Hooks, functional components have gained more capabilities, making them a preferred choice in many cases.

reactjs
functional-components
class-components