score:2
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'])
Source: stackoverflow.com
Related Query
- Infinite Loop when using setState for array
- How to prevent infinite loop in my React code when using setState inside useEffect
- Infinite loop when pushing into array using UseState()?
- this.setState is not pushing items into an array when using a for loop in React
- For loop not working in React when using setState (DOM not showing up updated data)
- Infinite loop when using array map
- React: Infinite loop when using custom hook inside of useEffect?
- React / Javascript for loop - Start from idx 0 when exceeding array length
- How to stop an infinite loop in javascript when using axios?
- Infinite useEffect loop when using Redux with React Hooks
- Error: Maximum update depth exceeded. This can happen when a component repeatedly calls... infinite loop when trying to setState
- prevent infinite loop when calling setState in useCallback
- Syntax question in relation to updating state using setState in a for loop
- React re renders all items in array when new items are added despite using unique keys for all items
- TypeError when making Columns for React-Table using array of objects as Data
- Infinite loop when using useLazyQuery in React + Apollo/GraphQL?
- React lazy import doesn't work when using inside for loop
- How do I avoid an infinite loop in useEffect when using Typescript?
- In React, when using map() to loop through an array of elements, does the result need to only be displayed using the <ul> and <li> tags?
- Infinite loop when setting and using state in a `useCallback` that is being called from a `useEffect`
- Eslint error when using the for in loop how to restructure
- How to covert object array to Array List using for loop
- Infinite for loop in useEffect when i want to check if a property of window object is here
- For loop behaving when trying to clear all items asynchoronously when trying to remove all id's in an array of id's
- How do I avoid infinite loop when using Redux state in useEffect dependency array?
- Infinite Loop When Using Hooks in React
- React - infinite loop using get request when using useState hook
- setState doesn't set state properly when used in array map function (we aren't using hooks its old project)
- How to push into array and setState for multiple properties in a loop
- Infinite Loop when setting setState hook as class attribute in Effect hook
More Query from same tag
- How to design the React component properly?
- Typescript exporting key/value object with react component as value
- How to store inCart value in localStorage?
- How to type a ref parameter with Typescript
- react-router-dom hot reloading using create-react-app
- Why can't my server access my build folder?
- React native cannot read property 'navigate' is undefined error
- react password eye icon for multiple fields
- Using nested routes with react-route
- SharePoint Framework React Button call within grid (loop)
- How to pass prop to react router component via NavDropdown.Item link
- Find percentage value in a nested arrays of object in javascript
- React-Router npm package giving me warning in console? (PropTypes deprecated)
- How to solve double API fetch on universal ReactJS
- How do you rerender a React component when an object's property is updated?
- I am trying to connect Lottery Contract to React Application using Metamask, But when I call manager() method on the contract I get an empty array
- Why it is appending the Previous object to array when i append the new object to it using useState hook?
- How to enable file upload on React's Material UI simple input?
- Second argument in reactjs function is undefined
- How to prevent form posting in <input type=submit> on click using React
- Trying to create a controlled switcher button
- trying to access a collection with uid, firestore
- How to test React.js component appearance?
- TypeError: Cannot read property 'handleClick' of undefined React JS
- React render same element which is dynamic component
- redux update state value without changing initial state
- Do React hooks need to return a value?
- How to create a variable that sets data asynchronously and is shared across many instances of a hook without multiple asynchronous calls?
- getInitialProps does not work with async function
- Does installing npm react react-dom in create react app is necessary?