-2

I am new to react and learning it via reactjs.org "Tic Tac Toe" tutorial, i have question on below.

function Square(props){
    return(
        <button className="square"
            onClick={() => props.onClick()}>
                {props.value}
            </button>
    );
}

Can be written as

function Square(props){
    return(
        <button className="square"
            onClick={props.onClick}>
                {props.value}
            </button>
    );
}

However below is incorrect

function Square(props){
    return(
        <button className="square"
            onClick={props.onClick()}>
                {props.value}
            </button>
    );
}

Can someone explain why "onClick={props.onClick()}" is incorrect however both "onClick={() => props.onClick()}" and "onClick={props.onClick}" are correct.? When using "onClick={props.onClick()}" it compiles fine however react throws below error at run time. Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

Sunil Thakur
  • 97
  • 2
  • 11

2 Answers2

0
onClick={props.onClick()}

This one means "immediately call props.onClick(), and pass it's result into the onClick prop". Assuming props.onClick returns undefined, you're passing undefined into the click handler, so nothing will happen when it's clicked.

onClick={() => props.onClick()}

This means "create a function with the text () => props.onClick() and pass it into the onClick prop". Later, when a click happens, the function will be run, which in turn will run props.onClick.

onClick={props.onClick}

This means "pass props.onClick into the onClick prop". Later, when a click happens, props.onClick will be run.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

onClick={props.onClick()} is executing when the component is rendered.

onClick={() => props.onClick()} will be executed when the user click, but can be passed params directly, like this: onClick={() => props.onClick(this, id)}

onClick={props.onClick} will be executed when the user click, passing the event as a param. In this approach, you are passing a reference.

Related question: What is the difference between a function call and function reference?