Home > Net >  In a simple react functional component can useState called twice?
In a simple react functional component can useState called twice?

Time:05-11

In a simple react functional component can useState called twice?

const MyComponnet = () => {
   let myRandom = Math.floor(Math.random() * 10);
   const [number, setNumber] = useState(myRandom)
   ....
   ....
}

If this component re-render, we will have a new myRandom, does that cause us to reset state to new random number,

CodePudding user response:

If this component rerenders, then you might have a new value for myRandom, but number will not take that value. That is the point of state variables. They maintain value over rerenders and infact change in them cause rerenders.

But if the component unmounts and mounts again, the state variable number will again be filled by the variable myRandom.

Difference

CodePudding user response:

No it wont, because useState preserves the state over multiple renders. However, it will be a good idea to keep initial state i.e. "myRandom" outside the component so it does not get computed on every render.

  • Related