score:2

Accepted answer

i believe you may be experiencing issues because calling setstringarray is a 'side effect'.

this will cause the function component to be re-rendered infinitely, due to the hook having updated the component's state, causing a re-render which then updates the state and on and on infinitely.

essentially, you shouldn't be trying to both read and update strarray in the same line.

you should simply only call the setstrarr once after having fully populated your array.

i think you should also look into using the useeffect hook for behaviour like this.

the last parameter it get's passed tells react to only run the code inside of this useeffect hook if the paramater given (strarray in this case) changes.

this hook is designed for when you want to have 'side effects' in your component.

so perhaps you could try something like to prevent your infinite re-renders:

function myapp(){
  const [strarr, setstrarr] = usestate([]);

  useeffect(() => {
     const fourhiarray = [];

    for(let i = 0; i<4; i++){
       fourhiarray = ([...fourhiarray, "hi"])
       if(i==3){
          console.log("done")
       }
    } 

    setstrarr(fourhiarray);
  }, [strarr]);
       
  return(
    <div>
    </div>
  )
}

score:0

adding on to the other answers, since you are executing synchronous code i would the use the uselayouteffect hook. uselayouteffect runs, and react waits for it to finish. this is fine for react to wait since the code is all synchronous and it prevents your component from "blinking" on screen because useeffect gets called after render is done.

function myapp(){
  const [strarr, setstrarr] = usestate([]);

  uselayouteffect(() => {
     let fourhiarray = [];

    for(let i = 0; i<4; i++){
       fourhiarray = ([...fourhiarray, "hi"])
       if(i==3){
          console.log("done")
       }
    } 

    setstrarr(fourhiarray);
  }, []);
       
  return(
    <div>
    </div>
  )
}

score:1

on rerender whole function myapp is called, thus on every rerender your cycle is started anew. if you only want to call it once call it in useeffect. like so

useeffect(() => {*your code here*}, []}

useeffect with empty array as second param is only called on first render.

also if you want to set your inital state i would recomend doing it in usestate(['hi','hi','hi','hi'])


Related Query

More Query from same tag