0
votes

I have a main component that gets rendered on the "/" route (which is set up on index.js). There's a common search bar in App that's rendered above/outside of it's own child routes. Basically I want this search bar to be common across the application. The search bar updates a property on App state whenever there's a change. It works OK in all routes except for the fact that every time I type in the search bar in a child route, App along with the current child route component gets re-rendered. How can I prevent this re-rendering, since there are no prop changes and no need to re-render the child component?

// App.js
render()
...
    <SearchBar
      className={classes.searchbar}
      value={(this.state.query && decodeURI(this.state.query)) || ''}
      onChange={this.handleQueryChange}
      inputRef={(el) => el && el.focus()}
      onRequestSearch={this.handleSearch}
      style={{
        margin: '0 auto',
        maxWidth: 800
      }}
    />
...
            <Route
              path="/:projectName/admin"
              render={(props) => (
                <Admin
                  {...commonProps}
                  handleError={this.handleError}
                  updateIsLoadingResults={this.updateIsLoadingResults}
                />
              )}
            />
1
Can you set up a small fiddle on codesandbox.io/s/new. Include your index/routes/searchbar and one child component. From the code above, there isn't enough information to understand why/what is causing the re-rendering.Matt Carlotta

1 Answers

1
votes

React doesn't inherently know that a component doesn't need to re-render a child component when the state changes. Instead, it errs on the side of caution and re-renders everything below the component where the state change occurred. To tell React that your component should not re-render when this happens, you should use shouldComponentUpdate or React.PureComponent. PureComponent is useful if you are managing your state/props an immutable way, whereas shouldComponentUpdate allows for more custom logic.

I would recommend benchmarking different methods and only utilize these optimizations if you see a measurable difference in performance. React is generally pretty fast at rendering and doesn't actually change the DOM unless it needs to. If your render functions are slow, I would recommend looking into what is making them slow and optimizing there.

Here is an example that uses PureComponent to avoid re-rendering. Keep an eye on the console logs to see the difference between the two child components.