Too many re-renders

When I render this component that is a client component of a dashboard slug, it breaks the entire page and re-renders so many times that it force stops. I store the id of a project inside of the url like this
http://localhost:3000/dashboard/99c7fd81-1001-47b5-bf19-5e48beee5861
http://localhost:3000/dashboard/99c7fd81-1001-47b5-bf19-5e48beee5861
I want to display the route of the url (dashboard, notes, settings) in the DashNav. example in image. This is how I do that now, but it completely breaks my entire page. Is there a better way to do this?
const DashNav: React.FC<NavProps> = ({project}) => {
const [isMenuOpen, setIsMenuOpen] = useState(false)
const [currentPage, setCurrentPage] = useState('')
console.log(project)
if (typeof window !== 'undefined') {
const pathname = window.location.pathname
if (pathname.startsWith('/projects')) {
setCurrentPage('projects')
} else if (pathname.startsWith('/dashboard')) {
setCurrentPage('dashboard')
} else {
console.log('Displaying settings');
}
}
const DashNav: React.FC<NavProps> = ({project}) => {
const [isMenuOpen, setIsMenuOpen] = useState(false)
const [currentPage, setCurrentPage] = useState('')
console.log(project)
if (typeof window !== 'undefined') {
const pathname = window.location.pathname
if (pathname.startsWith('/projects')) {
setCurrentPage('projects')
} else if (pathname.startsWith('/dashboard')) {
setCurrentPage('dashboard')
} else {
console.log('Displaying settings');
}
}
No description
Solution:
Think of react components as running top to bottom, and every time you call 'setState', it tells react to put in a request for the component to be re-rendered top to bottom. In your react, every render will call a set state, and trigger a rerender
Jump to solution
2 Replies
Solution
Josh
Josh8mo ago
Think of react components as running top to bottom, and every time you call 'setState', it tells react to put in a request for the component to be re-rendered top to bottom. In your react, every render will call a set state, and trigger a rerender
Josh
Josh8mo ago
The API your looking for in this case is usePathname, or you could use a more generic useSelectedLayoutSegment