DEV Community

Cover image for How to use functions in react class components?
aoda
aoda

Posted on • Edited on

1

How to use functions in react class components?

I know how you felt when you first saw this title, trust me, i know what were you thinking?

Are you joking? Use function?

That's too easy, right? const addition= () => {}
And then use it, just make it?

But, but, for beginners, I believe there will be some problems that you will meet

Now,there is a requirement. Every time the number is clicked, the number will increase by 1.

Bad use case ❌

1.The addNum will not take effect, and also has this error message

Image description

import React, { PureComponent } from "react";

export default class Demo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      num: 0,
    };
  }

  addNum() {
    const { num } = this.state;
    this.setState({
      num: num + 1,
    });
  }

  render() {
    return (
      // Use addNum method directly 
      <div onClick={this.addNum}>
        <div>add</div>
        <div>{this.state.num}</div>
      </div>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

2.The page will crash when use this method

Image description

import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      num: 0,
    };
  }

  addNum() {
    const { num } = this.state;
    this.setState({
      num: num + 1,
    });
  }

  render() {
    return (
      // Use addNum method directly 
      <div onClick={this.addNum()}>
        <div>add</div>
        <div>{this.state.num}</div>
      </div>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Good use case ✔

1.Use arrow function calls

import React, { PureComponent } from "react";

export default class Demo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      num: 0,
    };
  }

  addNum() {
    const { num } = this.state;
    this.setState({
      num: num + 1,
    });
  }

  render() {
    return (
      <div
        onClick={() => {
          this.addNum();
        }}
      >
        <div>add</div>
        <div>{this.state.num}</div>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

2.Declare addNum method using arrow function

import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      num: 0,
    };
  }

  addNum = () => {
    const { num } = this.state;
    this.setState({
      num: num + 1,
    });
  };

  render() {
    return (
      <div onClick={this.addNum}>
        <div>add</div>
        <div>{this.state.num}</div>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

3.Bind this

import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      num: 0,
    };
    this.addNum = this.addNum.bind(this);
  }

  addNum() {
    const { num } = this.state;
    this.setState({
      num: num + 1,
    });
  }

  render() {
    return (
      <div onClick={this.addNum}>
        <div>add</div>
        <div>{this.state.num}</div>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Or you can upgrade react version to 16.8, then use hooks 😂
Because we need to consider this pointer problem in class component, i hate this,that is a devil!!!!!

Then you never need to consider this when you use hooks function component ❤

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

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