sigvamo
sigvamo

Reputation: 55

How to avoid extra rendering in react with redux

I have next object:

Book = {
    id: 1,
    titel: "Some Book",
    sections: [
                {id: 1,
                 titel: "Section Titel",
                 pages: [
                          {id: 1, content: "Some text"},
                          {id: 2, content: "Some text"},
                          {id: 3, content: "Some text"}
                        ]
                },
                {id: 2,
                 titel: "Section Titel",
                 pages: [
                          {id: 1, content: "Some text"},
                          {id: 2, content: "Some text"}
                        ]
                }
              ]
}

Book object stored in Redux store (state.Book).

I have component which visualizes this Book object.

Component Book renders one or more Section components and each Section component renders Page component.

Book subscribed to Redux over connect function from react-redux and listens to store.Book, hole object.

It is clear that when titel of the Book will change then hole Book object will be re-rendered including all Sections and Pages.

There are two questions:

  1. Will react engine really re-render Sections and Pages if only Book.titel changed? Or it will identify that other parts of the component do not changed and will not re-render them.

  2. If it will re-render then what is the best way to avoid it? Should I subscribe Section and Page component to the Store also? But it will not solve the problem, because Book listens to hole state.Book object. Or should I subscribe Book component only to state.Book.id and state.Book.titel, then use this.context.store inside to path data to the inner components?

Thanks in advance.

Upvotes: 2

Views: 825

Answers (1)

Emilio Rodriguez
Emilio Rodriguez

Reputation: 5749

  1. Yes, React will call the render method in Sections and Pages but don't be worried about performance as those are really inexpensive operations. The Virtual DOM will abstract all the heavy operations (i.e. manipulating the DOM) minimizing the impact on performance. You can run some quick tests yourself to see how the UX is not affected at all by changes this size.
  2. I would not recommend to prevent re-rendering (as I said in #1 it's an unexpensive operation) but if you really want to, you could use shouldComponentUpdate in the Section components. You just need to return false whenever you feel the Section or their child components don't need to render

Upvotes: 2

Related Questions