Edwin
Edwin

Reputation: 69

My React button click logs twice for every single click

Image of my log

Whenever I click on the button in my child Component, it logs twice for every single click. I discovered this by simply adding a console.log(this.props) in my child components render function. This is the code below

Parent Component

import React, { Component } from "react";
import Counter from "./counter";

class Counters extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: 0,

    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ value: this.state.value + 1 });
  }
  render() {
    return (
      <div>
        <Counter onClick={this.handleClick} value={this.state.value} />
      </div>
    );
  }
}

export default Counters;

Child Component

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

class Counter extends Component {
  render() {
    console.log(this.props);
    return (
      <div className="container">
        <span className="badge badge-secondary">{this.props.value}</span>
        <button
          onClick={this.props.onClick}
          type="button"
          className="btn btn-primary m-2"
        >
          Increment
        </button>
      </div>
    );
  }
}

export default Counter;

Upvotes: 1

Views: 381

Answers (1)

HMR
HMR

Reputation: 39270

This is because your app is wrapped in <React.StrictMode> that can cause render functions, or functional components to be called multiple times for debugging purposes.

Upvotes: 1

Related Questions