Why function getSth
is called (can see console.log
s) every time component rerenders (by changing isSth
value on button click) although it isn’t changing the randomValue
state?
import React, { useState } from 'react';
function getSth() {
console.log('init');
return Math.random();
}
function Home() {
const [randomValue, setRandomValue] = useState(getSth());
const [isSth, setIsSth] = useState(false);
console.log(randomValue);
const onClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setIsSth((prev) => !prev);
};
return (
<button type="button" onClick={onClick}>
Click me
</button>
);
}
export default Home;
but when I do this, getSth
is actually called once?
const [randomValue, setRandomValue] = useState(0);
useEffect(() => {
getSth();
}, []);