DEV Community

Cover image for React State Variable: From Class Pains to Functional Elegance
Jorjis Hasan
Jorjis Hasan

Posted on • Updated on

React State Variable: From Class Pains to Functional Elegance

Suppose we want to make a simple counter app. The app will have basic counter functionality.

Let's visualize the app:
Visual illustration of description

Assuming the visual illustration, I'm gonna make this functionally and classically.

Functional Approach:

const MakeCounter = () =>{
    const [count, setCount] = useState(0);
    const handleClick = ()=>setCount(count+1);

    return(
        <div>
            <h1>Count: {count}</h1>
            <button onClick={handleClick}>Increment !</button>
        </div>
    )
}

export default MakeCounter;
Enter fullscreen mode Exit fullscreen mode

Classical Approach:

import React from "react";

class MakeCounter extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0,
    };
  }

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

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

export default MakeCounter;
Enter fullscreen mode Exit fullscreen mode

Now we can understand how painful it was back in times when we wrote state variables in the classical approach. we had to write 2x more code than the modern approach nowadays.

Top comments (0)