DEV Community

Cover image for React Functional Hooks Components > Stateful Class Components
Yasser Beyer
Yasser Beyer

Posted on • Edited on

2 2

React Functional Hooks Components > Stateful Class Components

With a quick glance at the examples below, it's immediately clear that with hooks:

  • managing state is simplified
  • there is no more dealing with "this"
  • code is much shorter
  • life is much better

Stateful Class Component

import React, { Component } from "react";

class ClickCount extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 1 };
    this.clickHandler = this.clickHandler.bind(this);
  }

  clickHandler() {
    this.setState({ count: this.state.count + 1 });
  };

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

Functional Component with Hooks

import React, { useState } from "react";

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

  function clickHandler() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={clickHandler}>Click me</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Hooks was introduced with the release of React 16.8. Follow this link to learn more about React Hooks.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay