9

Is it possible to rerender an element of an array, preventing others rerender?

Example: Having an array of 500 <Card> components and editing <Card> number 27 (which updates myArray props), I would like to rerender only <Card> number 27.

render = () => {
    this.props.myArray.map(card => {
        return <Cards key={card.id} ...card />
    })
}

In my case, <Card> components are a bit heavy and I would like to avoid rerendering them if they didn't individually change, but as soon as myArray prop changes and fires render() method, every single <Card> is being rerendered, causing some performance issues on every <Card> change.

james
  • 311
  • 5
  • 10
  • Possible duplicate of [ReactJS updating a single object inside a state array](https://stackoverflow.com/questions/32238679/reactjs-updating-a-single-object-inside-a-state-array) – David Zemens Sep 19 '19 at 16:48
  • 2
    Trying making `Card` a [`PureComponent`](https://reactjs.org/docs/react-api.html#reactpurecomponent) or using [`shouldComponentUpdate`](https://reactjs.org/docs/react-component.html#shouldcomponentupdate) in it. – Gabriele Petrioli Sep 19 '19 at 17:01

3 Answers3

2

Finally I've solved the issue by using shouldComponentUpdate() method in Card component as Gabriele suggested, even if Card component is part of the updated array, it will keep the previous rendered state if shouldComponentUpdate() returns false.

james
  • 311
  • 5
  • 10
0

James' answer is very useful for me. If you use React Hook, use React.memo and prevProps with nextProps to implement shouldComponentUpdate().

(fyi: https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate)

bychung
  • 93
  • 1
  • 4
-1

Use memoization in your component.If it doesn't change, the respective component is not rerendered. Googling "react memoize" will bring you a lot of nice resources. I'd also improve your Card component to receive a Card object instead of every card attribute. Deconstructing the card object can make your life harder writing the code to memoize it.

render = () => {
    this.props.myArray.map(card => {
        return <Cards key={card.id} card={card} />
    })
}
Jodevan
  • 732
  • 1
  • 6
  • 20
  • 7
    "Use memoization in your component." This answer could be improved by explaining, or showing, what that means! – Jake Worth Sep 19 '19 at 17:35