onClick() causing a Maximum update depth exceeded error

Viewed 52

In the render method, why does it not like this.increment in the onClick attribute? I'm not sure how the maximum update depth error relates. Sorry, I'm new to react and couldn't find much documentation on this.

import React, { Component } from 'react'

class Counter extends Component {
    constructor(props) {
        super(props)

        this.state = {
            count: 0
        }
    }

    increment() {
        this.setState(
            {
                count: this.state.count + 1
            },
            () => {
                console.log('Callback value', this.state.count)
            }
        )
    }

    render() {
        return (
            <div>
                <div> Count - {this.state.count}</div>
                <button onClick={this.increment()}> Increment </button>
            </div>
        )
    }

}
export default Counter
2 Answers

You need to make onClick refer to this.increment not calling it.

To fix the issue do this onClick={this.increment} or onClick={() => this.increment}. I also suggest you to do a quick reading on Event Handling in the official documentation.

onClick={this.increment()} to onClick={this.increment}. You have to refer a pointer to the function on onclick.

Related