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

108
Vistas
how to calculate default value for react js state hook with a function?

I'm doing something like this:

function App() {

  const [state1, setState1] = useState([1,1,1,1,1,1]);
  const [state2, setState2] = useState(MyFunction());

  return (
    <div className="App">
    <button onClick={() => setState1([1,2,3,4,5,6])}>test</button>
    </div>
  );
}

const MyFunction= () => {
  alert("MyFunction");
  return 5;
}

The strange thing is that the line alert("MyFunction"); is triggered 2 times on load and 2 times on every click on test button.

I'm very new to React.js and I don't understand this behavior.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

To answer your question:

how to calculate default value for react js state hook with a function?

useState allows a function as a 'initial state factory', like e.g.:

const [ state, setState ] = useState( function(){ return Math.random(); } );

So if you want to use your MyFunction as a factory, just use it this way:

const [ state2, setState2 ] = useState( MyFunction );

why is MyFunction called on every click ?

A React functional component is just a javascript function.

React decides when to call this function, which is basically whenever something changes. A call of some setState() is one reason why React will call the function of the functional component again (your App() function in this case).

But I suggest you consider the App() function to be called "whenever React wants to call it", or "all the time, again and again". Meaning you should not rely on when the function of the functional component is called, you should instead rely on the guarantees which React makes regarding when the state is up-to-date, specifically useEffect, useState, ...

MyFunction() is just a function call, which is inside the App() function call, so - of course - MyFunction() is called whenever App() is called (which is "again and again").

Why is the alert() called twice ?

The functional component is called 2 times in Strict Mode. This causes unexpected behavior only if you aren't using React as it is supposed to be used (which is something that just happens for React-beginners).

If you are using React in the intended way, you should not have to care about if the function is called once, twice or multiple times. The only thing that counts is what the state is.

See also e.g. React.Component class constructor runs once without console.log?

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