Manawasp
Manawasp

Reputation: 557

Can I avoid re-rendering parent route handler component when the route changes?

I'm noobies in react / redux and I'm looking to create modal view following this 3 rules :

Cause of the url dependancy it's not optimized, it's rerender the parent.

Example: I have a view namespaces view at '/namespaces' who print all namespaces and when I open '/namespaces/edit' who open the modal view the namespaces is rerender. How to not rerender the namespaces list ?

Below the Router

<Route path="namespaces" component={NamespaceList}>
   <Route path="edit" component={NamespaceEdit}/>
   <Route path="create" component={NamespaceCreate}/>
</Route>

NamespacesList component

function NamespacesList({ push, children }) {
  console.log("rendered !")
  return (
    <div>
      NamespacesList
      <p>
        <Link to="/namespaces/create">Create</Link>
        <br />
        <Link to="/namespaces/edit">Edit</Link>
      </p>
      {children}
    </div>
  )
}

NamespacesCreate component (printed inside of the modal)

const NamespacesCreate = function() {
  return (
    <Modal>
      NamespacesCreate
      <p>
        <Link to="/namespaces">Back to namespaces list ?</Link>
      </p>
    </Modal>
  )
}

Use case : I'm on the /templates/create (namespacelist is drawing in the back of the modal, in the console rendered ! is printed then when I click to link to comeback to the parent url /templates, rendered ! is printed again.

So there is a way to "optimize" it and not rerender the namespaceList or I need to choose between, or am I wrong ?

Upvotes: 4

Views: 1116

Answers (1)

Dan Abramov
Dan Abramov

Reputation: 268255

Don’t worry about how many times the component’s render() method is called. Rendering is very cheap in React, and if the content has not changed, it will not actually touch the DOM.

You should only start worrying about render() method calls when you start to experience real performance problems in your app which is very unlikely for one-off things like navigations. For example, you might want to optimize animations or form components that have ton of inputs.

If and when you have this problem (not earlier!), you can check out React guides to Advanced Performance optimizations, measuring wasted renders with ReactPerf, and learn about common performance anti-patterns.

Don’t let this complicate your code for no reason though. Only optimize when you have a real problem, and no sooner. React is very fast for most users’ needs out of the box, and render() method being called often is perfectly fine.

Upvotes: 2

Related Questions