React Functional Components

Functional components are JavaScript functions that return JSX and are the modern standard for building React applications. They are simpler, easier to read, and support hooks for state and lifecycle management.
  • Defined as plain JavaScript functions.

  • Use React Hooks (e.g., useState, useEffect) for state and side effects.

  • No need for this keyword.

  • Preferred over class components in modern React.

  • Easier to test and reuse.

import React, { useState, useEffect } from 'react';

function FunctionalComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Component mounted or updated');
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

export default FunctionalComponent;

React Class Components

Class components are ES6 classes that extend `React.Component` and include lifecycle methods and internal state. They were widely used before hooks were introduced.
  • Must extend React.Component.

  • Use this.state to manage state.

  • Use lifecycle methods such as componentDidMount, componentDidUpdate, componentWillUnmount.

  • Require this keyword and binding for event handlers.

  • Being gradually replaced by functional components with hooks.

import React, { Component } from 'react';

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

  componentDidMount() {
    console.log('Component mounted');
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

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

export default ClassComponent;