Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda