Marcin Wasilewski
Marcin Wasilewski

Reputation: 735

React-router - component reloads on parent component state change?

In my React app, I have a ResponsiveDrawer component taken from material-ui's demo. It's basically just a React component which renders a drawer with a list of menu items, a title bar and content frame.

It has mobileOpen in its state

state = {
    mobileOpen: false
};

which changes when user clicks the hamburger icon

handleDrawerToggle = () => {
    this.setState({ mobileOpen: !this.state.mobileOpen });
};

(...)

<Drawer type="temporary" anchor="left" open={this.state.mobileOpen} classes={{paper: classes.drawerPaper}} onRequestClose={this.handleDrawerToggle} ModalProps={{keepMounted: true // Better open performance on mobile.}}>
    <div>
        <div className={classes.drawerHeader} />
        <Divider />
        <MenuList onRequestClose={this.handleDrawerToggle} />
    </div>

I also have set up some routes inside the content of the ResponsiveDrawer:

<main className={classes.content}>
    <div className={classes.contentWrapper}>
        <Switch>
            <Route
                exact
                path="/currencies"
                component={CurrenciesComponent}
            />
            <Route
                exact
                path="/"
                component={ProfileComponent}
            />
            <Route component={NotFoundComponent} />
        </Switch>
    </div>
</main>

CurrenciesComponent from the route is defined as follows:

const CurrenciesComponent = () => (
        <Currencies isSignedIn={this.isSignedIn} />
    );

When I click the hamburger icon, the state of ResponsiveDrawer changes, however the CurrenciesComponent is also reloaded (I have an API call there which takes a few seconds to complete so I would like to avoid this).

If I define my route as follows (without passing the props to Currencies component), this doesn't happen:

<Route exact path="/currencies" component={Currencies} />

So how do I avoid the re-render and provide props to Currencies at the same time when specifying the route?

Upvotes: 2

Views: 1645

Answers (2)

Marcin Wasilewski
Marcin Wasilewski

Reputation: 735

I solved the issue by using render instead of component prop for my routes:

<Route exact path="/currencies" render={CurrenciesComponent}/>

Upvotes: 4

MynockSpit
MynockSpit

Reputation: 449

You can tell your component if it should update.

As part of React's lifecycle, each component has the method shouldComponentUpdate that gets run each time it gets a signal to update. Returning true from this function will tell the component to update and false will tell it not to.

Since all you're doing is asking it not to render if the props remain the same, you may be able to use PureComponent instead of Component. PureComponent implements shouldComponentUpdate and doesn't update unless props or state has changed.

Upvotes: 0

Related Questions