DEV Community

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

Posted on • Updated on

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)