6

I have a connected (to a redux store) component. I have multiple routes that all use this component in a render prop. On every route change, the entire component appears to be re-mounted. Is there any way to prevent this from happening? My first thought was that I may be re-instantiating the component every time, due to the render prop being a function that react router calls? Here's some code:

const routeFunction =
  (resource, props) => <CrudWrapper resource={resource} modelId={props.match.params.id} />

export default crudResources.map(resource => ({
  path: `/${resource}/:id?`,
  link: `/${resource}`,
  resource,
  // eslint-disable-next-line react/prop-types
  render: routeFunction.bind(null, resource)
}));

The routes are then mapped in JSX: {routes.map(route => <Route key={route.path} {...route} />)}

I had the routes wrapped in a <Switch> and thought this might be causing the issue, but even after removing the switch, the component's componentWillMount method is called every time.

t_rm
  • 111
  • 2
  • 6
  • 1
    `{routes.map(route => )}> When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. – Omar Feb 26 '18 at 15:55
  • 1
    How would I prevent this then, Omar? I have to use the render prop in order to pass in the resource. Is there any way to instantiate it once and re-use it in the render prop? – t_rm Feb 26 '18 at 16:14

1 Answers1

0

The problem appears to be related to the key prop on the route. When I omit the key prop, the Component is not remounted. As soon as I add it, no matter what the string is, the route is remounted.

EDIT:

This was my bad. Since all routes have different keys, react will remount them since they are all different. See here: https://github.com/ReactTraining/react-router/issues/5972

t_rm
  • 111
  • 2
  • 6