Skip to content

React Function and Class Components

Updated: at 11:00 AM

In React, you have two main ways to define components: function components and class components. Both serve the same purpose—to create reusable blocks of UI—but they have different approaches and use cases.

Function Components:

Example:

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

Class Components:

Example:

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

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

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={this.handleClick}>Click me</button>
      </div>
    );
  }
}

Another ways sample React JS Function and Class components

Function component

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Class component

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

Demo

import React from "react";
import ReactDOM from "react-dom";

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

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

const element = <Welcome name="Eka" />;
const elementClass = <WelcomeClass name="Eka" />;

ReactDOM.render(element, document.getElementById("root"));
ReactDOM.render(elementClass, document.getElementById("root-class"));

Choosing the Right Component:

Additional Considerations:

Ultimately, the best choice depends on your specific component’s needs and complexity. Consider all factors and experiment to find what works best for you and your project.

Thank you for reading this article, I hope you find it useful. Happy coding! 🔥