useState Hook inside loop or conditional statement

Viewed 464

I was reading the updated react docs whose link is here there is statement related to useState

If you want to useState in a condition or a loop, extract a new component and put it there.

But what I know by the rules of hooks is that you cannot use hooks inside loops, conditions, or nested functions which is mentioned in the docs here

So can someone give an example of the first sentence, because they didn't gave an example or there.

My question is can we call hooks inside loops and conditional statements ?

2 Answers

What they are saying is that if you want to have something with state in loop component:

const App = ()=>{
const fields = [someArray]
return(
<div>{fields.map((field)=>{
              const [value, setValue] = useState() //wrong usage!
              return (<input 
                       onChange={(e)=>setValue(e)} 
                       value={value} 
                     />)})})
               
</div>
)}

You need to specify component that you wanna loop in new Component and use hook there:

const Input = ()=>{
 const [value, setValue]= useState()
 return <input 
             onChange={(e)=>setValue(e)} 
             value={value} 
      />
}

and use it in loop

const App = ()=>{
 const fiels = [someArray];
 return (
  fields.map((field)=>
   <Input />
   )
  )
}

const Input = ()=>{
 const [value, setValue]= useState()
 return <input 
             onChange={(e)=>setValue(e)} 
             value={value} */ Don't mutate state /*
      />
}

We should not be mutating state. React needs to compare it's virtual DOM to the current DOM to determine what to re-render. Futhermore, react hooks are asynchronous, meaning that value may not be updated to e at the point you try and assign to value. This was already achieved with setValue(e).

Related