0

I'm trying to optimize the performance of app. I've found that the issue is that one of my components re-renders on a condition that I set and it contains a significant amount of data. I wanted to know if it were possible to not re-render the whole component, but to only re-render the element that has changed?

I've already tried using PureComponent, but that did not have enough control for me. I'm currently using shouldComponentUpdate.

bitznbytez
  • 74
  • 1
  • 13

2 Answers2

1

By default every time a parent component is re rendered all the children nodes will be rendered as well, if you know for sure that a given component will always render the same content given the same props then you could turn it into a PureComponent, a pure component performs a shallow comparison obj1 === obj2 in props and only re-render when a change occurs. If you need a more complex comparison logic then shouldComponentUpdate is the way to go:

shoudComponentUpdate(prevProps, prevState){
    if(prevProps.items.length !== this.props.items.length) return true

    return false
}

By default this method always returns true, unless you explicitly tells it not to. The functional version of shouldComponentUpdate is React.memo. But keep in mind that comparisons take time, and the amount of processing required to perform a comparison grows with the complexity. Use it carefully.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dupocas
  • 20,285
  • 6
  • 38
  • 56
  • So, I've thought about your answer. I have an additional question. I'm thinking of extracting the portions of the component I do not want to update, into a Fragment (Fragments let you group a list of children without adding extra nodes to the DOM.). Since it does not add extra nodes, would this prevent re-rendering? – bitznbytez Jul 05 '19 at 20:05
  • No. Just wrap your components in a Fragment will not prevent then from render. Fragment is only used when you need to return adjacent JSX elements. Different things... – Dupocas Jul 05 '19 at 20:06
0

I would suggest breaking out the piece that needs to be updated into it's own component and use React.memo or PureComponent like you were saying. This might also help.

React partial render

Michael Cox
  • 1,116
  • 2
  • 11
  • 22