'Too many re-renders in React.JS

Hi I'm currenlty doing a side project for my portfolio and was wondering how did this error happen. It's a navbar component in react, with Link to other pages and button to set an active theme. Any Idea what is causing the infinite re-render? Thank you.

import React, {useEffect} from 'react'
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box'
import { Button } from '@mui/material';
import { Link } from 'react-router-dom';

const MenuBar = () => {
    const [activeItem, setActiveItem] = React.useState('')

    const handleItemClick = (e, {name}) => {
        setActiveItem(name)
    }
  useEffect(() => {
        const pathname = window.location.pathname
        const path = pathname === '/' ? 'home' : pathname.substring(1)
        setActiveItem(path) 
    }, [])

    return (
      <div>
        <AppBar color='primary' position={'static'}>
                    <Box className='flex items-center justify-between'>
                        <Link to={'/'} onClick={setActiveItem('home')}>
                            <Button variant='text' sx={{ bgcolor: activeItem === 'home' ? '#FDFFA9' : '#FFD365'}}>Home</Button>
                        </Link>
                        <Box>
                            <Link to={'/login'} onClick={setActiveItem('login')}>
                                <Button variant='text'>Login</Button>
                            </Link>
                            <Link to={'/register'} onClick={setActiveItem('login')}>
                                <Button variant='text'>Register</Button>
                            </Link>
                        </Box>
                    </Box>
                    
                </AppBar>

      </div>
    )
  
}

export default MenuBar



Solution 1:[1]

I think the problem is with the way you assign onClick handlers

onClick={setActiveItem('home')}

during rendering you actually invoke the action, not assigning the callback, so

render -> setActiveItem -> render -> ..

please try to assign as the fn value instead:

onClick={() => setActiveItem('home')}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 udalmik