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);
What is this? The issue is that the setCounter function gets invoked when the component renders, updates the state, which causes a re-render and does that infinitely. You could solve the error by passing an initial value or a function to the useState() hook to initialize the state.
1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.
To get rid of your infinite loop, simply use an empty dependency array like so: const [count, setCount] = useState(0); //only update the value of 'count' when component is first mounted useEffect(() => { setCount((count) => count + 1); }, []); This will tell React to run useEffect on the first render.
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With