My question is isn’t it almost as same as onClick rule in buttons? because we use () parentheses that causes it to run everytime the component renders and immediately. So I tried it without parentheses and found out that it works as intended. The generateAllNewDice function runs only one time when it first renders the component.
So did I just accidentally found another solution😅 or am I missing something? I would love to know what you think on this. Also many many thanks, it’s because of you and your simple but detailed lessons that learning react was nothing but a walk in the park
Yes, this way would also work. As long as you don’t need to pass any parameters to the generallAllNewDice function, either way will work just fine.
Under the hood, React simply checks to see if the value you pass to useState() is a function or not. If it is, it will call that function and set the returned value as the initial state. If it isn’t a function, it’ll just directly set the value passed as the initial state.
So in this case, useState(() => generateAllNewDice()) and useState(generateAllNewDice) would basically be identical. But if generateAllNewDice took an argument (e.g. numDice to pass in how many dice to generate), then you’d have to use an inline function: useState(() => generateAllNewDice(10))
Great job experimenting! That’s what Scrimba’s all about