Reputation: 417
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.
Upvotes: 3
Views: 1806
Reputation: 6073
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 );
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").
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?
Upvotes: 2