Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
React usestate with for loop error in rendering

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If you use setstate(myArrayMakingFunction) within a useEffect hook, this should work.

https://reactjs.org/docs/hooks-effect.html

about 4 years ago · Juan Pablo Isaza Report

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Report

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!