Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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')}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!