React_How to get a static value from Math.random()

Please consider the code below:

const number = Math.floor(Math.random()*10) //Gives a random number from 0 to 9

The problem with this method is that every time the component re-renders the number constant changes (re-assigned), is there a way to keep it constant?

You can set the number as null initially, and add an additional check. If “number” is null generate a random number and assign it or else leave it. (Singleton Pattern).

const rand = Math.floor(Math.random() * 10);

const MyComponent = () => (
    // Some JSX here, use rand

If you want the ability alter the random number (for example on a button click):

const MyComponent = () => {
  // The variable num will start as a random
  // number, then to change it need to call
  // the setNum function
  const [num, setNum] = React.useState(rand());

  // This function will set the num
  // variable to a new random mumber
  const setNewRand = () => setNum(rand())

  return (
      // Some JSX here, use rand, set using setNewRand 
1 Like

what is this? and where did you define the function setNum?

setNum is a function provided by React to set the state of num. Whenever you change state, you should use that (and only that) function.


There are several examples in the FCC JavaScript ES6 section of challenges.

And if you don’t understand this part of React, then as as a class component (rand is still a function defined somewhere else, although in both cases I’ve only done that for brevity):

class MyComponent extends React.Component {
  state = {
    num: rand()

  setNum = () => this.setState({ num: rand() });

  render() {
    return (
      // JSX here
1 Like