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!
2
Answers
The useState with an initializer function might be the most straight forward approach as it will be Clearer Intent code and the simplicity with usestate also improves the Performance ,Consistency with Other State and its Predictable Behavior.
Assign the random number to a variable outside of the component. No need for
useState
,useRef
,useEffect
, oruseMemo
at all.