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

Marcin Wasilewski Source

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 className={classes.drawerHeader} />
        <Divider />
        <MenuList onRequestClose={this.handleDrawerToggle} />

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

<main className={classes.content}>
    <div className={classes.contentWrapper}>
            <Route component={NotFoundComponent} />

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?



answered 9 months ago MynockSpit #1

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.

answered 9 months ago Marcin Wasilewski #2

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

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

comments powered by Disqus