0

I want to generate a random value integer in the range [0, 5] with each click of the button. Initially I get some random values on the console. But after some clicks, same number appears repeatedly on the console. Why?

'''

import React, { useState } from 'react'
import ReactDOM from 'react-dom'

const App = () => {
  const [selected, setSelected] = useState(0)
  const myRandom = Math.floor(Math.random() * 6)  

  console.log("selected", selected)
  console.log("myRandom", myRandom)

  return (
      <div>
      <button onClick={() => {setSelected(myRandom) } } >next</button>
      </div>  
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)

'''

norbitrial
  • 14,716
  • 7
  • 32
  • 59
GrozaFry
  • 41
  • 7

1 Answers1

0

Probably a better way to handle is using a proper function for onClick event and useEffect() hooks to capture changes for state values what you can log to the console.

Try as the following:

const [selected, setSelected] = useState(0);

const generateNewNumber = () => {
   setSelected(prev => Math.floor(Math.random() * 6));
}

useEffect(() => {
    console.log("selected", selected);
}, [selected]);

return <div>
  <button onClick={() => generateNewNumber()}>
     next
   </button>
</div>

Suggested read: Using the Effect Hook

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
  • Can you explain why your code keeps generating random numbers but mine doesn't? – GrozaFry Apr 17 '20 at 12:11
  • @GrozaFry In your case on initial render the value of `myRandom` generated once. On each click that value is being showed. In my case the `onClick` event triggers a function called `generateNumber()` where the code newly generates the value what we pass the `setSelected`. I hope this clarifies. – norbitrial Apr 17 '20 at 12:25
  • But I'm getting more than one random value. Sometimes I get 3 random values then start getting same values. Other times I get 2 random values then again start getting same values. In my code, every time the button is clicked, the App component should re-render. So shouldn't I get different values each time? – GrozaFry Apr 17 '20 at 14:23