Tested
Tested

Reputation: 789

Too many re-renders. React limits the number of renders to prevent an infinite loop. - React Hooks

I'm new to React hooks here, I've a sidebar I want to update the selecetedIndex to the index selected for that ListItem i.e., when I select an item I want to update selectedIdx to index to show it selected. I'm doing something wrong.

      <ListItem button key={index}
                selected={selectedIdx===index} // to show selected need to update
                onclick={setSelectedIdx(index)}
              >
                  <ListItemIcon>{v.icon}</ListItemIcon>
                  <ListItemText primary={v.text} />
      </ListItem>


 let [selectedIdx,setSelectedIdx]=React.useState(0);

This way second try I did but not results:

         <ListItem button key={index}
                        selected={selectedIdx===index}
                        onclick={handleSelectedIdx(index)}
                      >
                          <ListItemIcon>{v.icon}</ListItemIcon>
                          <ListItemText primary={v.text} />
         </ListItem>

function handleSelectedIdx(i){
    setSelectedIdx(i)}

I'm new I don't know how do we do this.setState in hooks. Both the ways it failed can anyone please let me know were I'm going wrong. Any help appreciated.

Updates: here I don't use:

{()=>{handleDrawerToggle}}

Still the following works why is that so? Can you please let us know?

<IconButton
        color="inherit"
        aria-label="Open drawer"
        edge="start"
        onClick={handleDrawerToggle}
        className={classes.menuButton}
      />

   function handleDrawerToggle() {
      setMobileOpen(!mobileOpen);  }

  const [mobileOpen, setMobileOpen] = React.useState(false);

Upvotes: 6

Views: 21640

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282000

The problem in you code is that you are not passing a function to onClick, rather a value returned by handleSelectedIdx/setSelectedIdx and since you set a state a re-render is triggered causing the function to execute again on the next render. React internally prevents this loop and warns you.

The solution is to write your onclick like

onClick={() => handleSelectedIdx(index)}

or even

onClick={() => setSelectedIdx(index)}

Upvotes: 13

Related Questions