DEV Community

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

Posted on β€’ Edited 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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

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

Okay