skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Assign the random number to a variable outside of the component. No need for useState, useRef, useEffect, or useMemo at all.

    const { useState } = React;
    
    function getRandomNum(max) {
      return Math.floor(Math.random() * max);
    }
    
    const rnd = getRandomNum(10);
    
    function Example() {
    
      const [ count, setCount ] = useState(0);
    
      return (
        <div>
          <p>Random number is {rnd}</p>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>
            Click me
          </button>
        </div>
      );
    
    }
    
    const node = document.getElementById('root');
    const root = ReactDOM.createRoot(node);
    root.render(<Example />);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
    <div id="root"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search