DEV Community

Md Yusuf
Md Yusuf

Posted on

React Components (Class-based vs Functional)

React components are the building blocks of any React application. They allow you to split the UI into independent, reusable pieces that can be managed and rendered separately. React components come in two main types: Functional Components and Class Components.

Functional Components
Functional components are simpler and are written as JavaScript functions. They take props (input data) as an argument and return JSX, which describes what the UI should look like. As of React 16.8, functional components can also handle state and side effects using hooks like useState and useEffect.

import React, { useState } from 'react';

const Welcome = (props) => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>You've clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
};

export default Welcome;

Enter fullscreen mode Exit fullscreen mode

Class Components
Class components were the original way to write components in React. They extend the React.Component class and must include a render() method that returns JSX. Class components can have their own state and lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

import React, { Component } from 'react';

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

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

  render() {
    return (
      <div>
        <h1>Hello, {this.props.name}!</h1>
        <p>You've clicked {this.state.count} times</p>
        <button onClick={this.handleClick}>Click me</button>
      </div>
    );
  }
}

export default Welcome;

Enter fullscreen mode Exit fullscreen mode

Key Concepts:

  • JSX: A syntax extension of JavaScript that looks like HTML. React components return JSX to describe the UI.
  • Props: Short for "properties", props allow you to pass data from parent components to child components.
  • State: A built-in object for storing dynamic data that affects what is rendered in the component. Only components that use state (either functional or class components) can re-render based on changes to this data.

Hooks (for functional components):

  • useState: Allows you to manage state in a functional component.
  • useEffect: Allows you to perform side effects in a functional component (e.g., fetching data, updating the DOM).

React encourages the creation of small, reusable components that can be combined to form larger applications, keeping the codebase modular and easier to maintain.

Top comments (0)