React "Cannot update a component (`BrowserRouter`) while rendering a different component" warning when registering a new user using firebase

Viewed 1523

I am working on a react project and I am using react-firebase-hooks to create or sign in users. Whenever I create a new user, this warning pops up, I am changing the login to a button to logout and redirecting the user to the home page after registering,

if (user) {
        navigate('/home');
    }

The error,

react-dom.development.js:86 Warning: Cannot update a component (`BrowserRouter`) while rendering a different component (`Register`). To locate the bad setState() call inside `Register`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
    at Register (http://localhost:3000/main.4ec98b661e1297c4a8cc.hot-update.js:259:64)
    at Routes (http://localhost:3000/static/js/bundle.js:77696:5)
    at div
    at App
    at Router (http://localhost:3000/static/js/bundle.js:77629:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:76438:5)
3 Answers

This is because the current page has not yet been rendered to the end. So use a redirect after the page is fully rendered, like so:

useEffect(() => {
    if (user) {
      navigate('/home');
    }
},[])

Almost ok. But you just need to set the dependency.

useEffect(() => {
    if (user) {
      navigate('/home');
    }
},[user])

Finally you if you have eslint on for react, it will yell at you to use both user and navigate to use as dependencies.

 useEffect(() => {
    if (user) {
      navigate('/home');
    }
},[user, navigate])
Related