What is the proper way to update multiple objects in an array of objects in react?

Viewed 79

Making a watchlist app for stocks/crypto to learn react.

I have watchlist state in this format (using useState hook):

      [
        { id: "1btc", name: "bitcoin", price: "7500" },
        { id: "1eth", name: "ethereum", price: "500" },
        { id: "2xmr", name: "monero", price: "200" },
        { id: "1ltc", name: "litecoin", price: "10" },
      ];

every 3 seconds server sends a batch of available price updates over websocket connection. sometimes only a handful of coins have new info so update message might look like so:

      [
        { id: "2xmr",  price: "225" },
        { id: "1btc",  price: "8600" },
      ];

Is it possible to update the watchlist so that only the updated coins in the list rerender as opposed to rerendering the entire list every time an update message is received? What is the best way to handle this situation?

1 Answers

You could let each object have its own component and then pass the object properties in the components and then use React.memo() so that it would only cause a render if it detects a change.

By default it will only shallowly compare the objects in the props which should be enough for you. But if its more complex, then you can also write a custom function.

As per docs

function MyComponent(props) {
  /* render using props */
}
function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);
Related