bobby
bobby

Reputation: 455

Why state change in App.js cause component remounting?

In App.js file I am doing routing (for routing I am using react-routesv4). With routes there is also sidebar. Cause of sidebar I have state that is controling that sidebar. Whenever sidebar state is changed other component that is connected with current route is remounting.

For example here I have component User that is remounting every time sidebar state is changed. And in component User i am fetching data with useEffects hook, so every sidebar state change also trigger that hook.

const App = ({classes}) => {

    const [isDrawerOpen, setIsDrawerOpen] = useState(false);

    const handleDrawerToggle = () => {
        setIsDrawerOpen(!isDrawerOpen)
    };

    return (
        <BrowserRouter>

            <CssBaseline/>

            <Switch>

               <Route path={'/login'} component={Login}/>

               <Fragment>
                  <Sidebar isDrawerOpen={isDrawerOpen} toggleDrawer={handleDrawerToggle}/>
                  <main role="main" className={classes.content}>
                      <Switch>
                          <Route exact path='/' component={User(Dashboard)}/>
                          <Route path='/users' component={Admin(Users)}/>
                      </Switch>
                  </main>
              </Fragment>

          </Switch>

      </BrowserRouter>
   );
};

export default withStyles(styles)(App);

const Authorization = (allowedRoles) => (WrappedComponent) => {
 const WithAuthorization = (props) => {

     const role = helpers.getRole();

     if(role === null){
         return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
     } else if (allowedRoles.includes(role)) {
         return <WrappedComponent {...props} />
     } else {
         return <Typography>You don't have access</Typography>
     }

   };

    return WithAuthorization;
};

export default Authorization;

Don't know what is causing that kind of behaviour?

Upvotes: 0

Views: 192

Answers (1)

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15831

This is due to the HoC being evaluated every render. Try:

const AuthorisedComponent = requireLogin(MyComponent); // instantiate hoc once

<Route path="/mycomponent" component={AuthorisedComponent} /> // use hoc

Upvotes: 1

Related Questions