I want to create an array with random values filled in it between 0 to 7 and use this array as state value but use it in for loop of functional component call for loop multiple times when console.log state value. This will create rendering error in react
import React from "react";
import "./style.css";
import { usestate} from "react"
export default function App() {
const [ state , setstate ] = usestate([]);
let arr = [] ;
for(let i = 0 ; i < 64 ; i ){
arr[i] = Math.floor((Math.random ()*8));
}
setstate(arr);
return (
<div>
<h1>State</h1>
<p>{state}</p>
</div>
);
}
Thank you
CodePudding user response:
If you use setstate(myArrayMakingFunction)
within a useEffect
hook, this should work.
https://reactjs.org/docs/hooks-effect.html
CodePudding user response:
Do this in componentDidMount phase.
import React, { useState, useEffect} from 'react';
import "./style.css";
export default function App() {
const [ state , setstate ] = useState([]);
useEffect(()=>{
let arr = [] ;
for(let i = 0 ; i < 64 ; i ){
arr[i] = Math.floor((Math.random ()*8));
}
setstate(arr);
}, [])
return (
<div>
<h1>State</h1>
{state?.map(i=><p key={i}>{i}</p>)}
</div>
);
}
CodePudding user response:
First, you need to import useState, instead of usestate. You need to import useEffect as well or it will cause many re-renders. Your solution is the code below:
import React, {useState, useEffect} from "react";
import "./style.css";
export default function App() {
const [ state , setstate ] = useState([]);
let arr = [] ;
for(let i = 0 ; i < 64 ; i ){
arr[i] = Math.floor((Math.random ()*8));
}
useEffect(()=>{
setstate(arr);
}, [])
return (
<div>
<h1>State</h1>
<p>{state}</p>
</div>
);
}