I need to generate a list of elements, each should have its own key. The key shouldn't be changed during the following renderings as this data is in use by other components. So, the task is: to create a list of unchanged random numbers and use them.
The problem is as soon as I use them as const, they are recalculated every next render. But if I put them into state, for some reason they can't see the actual value of other state variables.
const [t, setT] = useState(1);
function clickItem(){
console.log(t)
setT(t + 1)
};
// Case 1:
const randomItems = [Math.random(), Math.random()]
.map(i=><div key={i} onClick={clickItem}>{i}</div>);
// Case 2
const [list, setList] = useState([Math.random(), Math.random()]
.map(i=><div key={i} onClick={clickItem}>{i}</div>));
return (
<>{randomItems}
<hr></hr>
{list}
</>
);
When we click the items from the first list, they increase the "t" variable but change their values with each click.
When we click the items from the second list, they don't change their values but the value of "t" is always 1.