-1
import React,{useState} from 'react';

export function App(props) {
  const [fruit, setFruit ] = useState("apple")

  function settingFruit_1()
  {
    setFruit("mango");
  }

  return ( 
    <div className='App'>
      <h1>{fruit}</h1>
      //why am I getting the error when calling the function like this onClick = {settingFruit_1()}
      <button onClick = {settingFruit_1()}> submit </button> 
      
    </div>
  );
}

Here is the error that I see:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
    at renderWithHooks (<anonymous>:11510:25)
    at mountIndeterminateComponent (<anonymous>:14733:23)
    at beginWork (<anonymous>:15659:24)
    at HTMLUnknownElement.callCallback2 (<anonymous>:3454:24)
    at Object.invokeGuardedCallbackDev (<anonymous>:3479:26)
    at invokeGuardedCallback (<anonymous>:3513:41)
    at beginWork$1 (<anonymous>:18904:17)
    at performUnitOfWork (<anonymous>:18371:22)
    at workLoopSync (<anonymous>:18308:15)
lanxion
  • 1,350
  • 1
  • 7
  • 20
JThind
  • 13
  • 2

2 Answers2

1

onClick Function expects you to pass a reference to the callback that it executes when user click that button. But here you call that function in onClick.

Solution:

Try using below syntax:

<button onClick={settingFruit_1}>submit</button>

Rithick
  • 236
  • 1
  • 5
1
  1. You are invoking the function rather than passing it's reference to the onClick handler
<button onClick = {settingFruit_1}> submit </button> // only pass reference without the () 
  1. Why does this cause infinite rerenders? Because by invoking function directly, you are calling the functions directly, rather than calling after click. This causes rerender => component is set again => function invoked again => setFruits => rerender => .........
pilchard
  • 12,414
  • 5
  • 11
  • 23
lanxion
  • 1,350
  • 1
  • 7
  • 20