Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendered more hooks than during the previous render when adding a hook component

I have a useInput hook component that works like this:

useInput(
    <input placeholder="phone number" />,
    "phone"
  )

It gets an (input,inputName) and returns a hooked input component. When I want to dynamically change the visibility of existing input in my view, I get an error: Rendered more hooks than during the previous render.

{this.state.showMyInput && useInput(
        <input placeholder="phone number" />,
        "phone"
      )
}
like image 895
Hadi Ranjbar Avatar asked May 15 '19 07:05

Hadi Ranjbar


3 Answers

From react documentation you can't use a hook with conditionnal operator.

You can call hook all the time and store the result in a variable, and just condition the render instead.

const input = useInput(input, inputName);
...    
{this.state.showMyInput && input}
like image 156
nubinub Avatar answered Sep 20 '22 15:09

nubinub


As per the react docs, you shouldn't invoke hooks inside a conditional statement. Instead, use the conditional inside your hook: As explained here

like image 44
varevarao Avatar answered Sep 20 '22 15:09

varevarao


my problem was that I had used the useState hooks after a return statement on my code, like:

function myComponenet () {
   if(loading) {return <Loading/>}

   const [myVar, setMyVar] = React.useState({})

   // my main component UI begins here

   <View>.....</View>
}

I had to move this const [myVar, setMyVar] = React.useState({}) line, above the if statement and that solved my problem

like image 30
Mahdieh Shavandi Avatar answered Sep 20 '22 15:09

Mahdieh Shavandi