Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
While using useState hook and onClick event in react I get error when calling the function in onClick event
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)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

  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 => .........
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda