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?

Related Query

More Query from same tag