I do not want the value of random numbers to change with each rendering.
const getRandomNum = (max) => Math.floor(Math.random() * max)
1.With useEffect
const ComponentA = () => {
const [randomNum, setRandomNum] = useState(0)
useEffect(() => {
setRandomNum(getRandomNum(10))
}, [])
return <div>{randomNum}<div>
}
2.With useState initializer function
const ComponentA = () => {
const [randomNum] = useState(() => getRandomNum(10))
return <div>{randomNum}<div>
}
3.With useMemo
const ComponentA = () => {
const randomNum = useMemo(() => getRandomNum(10), [])
return <div>{randomNum}<div>
}
Thanks for reading!