skip to Main Content

Passing the full object into the component?

{list.map(
  (item => (
    <Child item={item} key={item.id} />
  )
)}

Or using destructuring?

{list.map(
  (({id, prop1, prop2, prop3}) => (
    <Child key={id} prop1={prop1} prop2={prop2} prop3={prop3} />
  )
)}

Maybe TypeScript can change or add the new approach somehow?

2

Answers


  1. There is no best option, as it depends on your use case. But there are subtle differences:

    In second case,

    1. it would be a lot easier to optimize using React.memo, as react compares props and decide whether it should re-render. Passing an object (which would probably be created fresh in every render) would defeat the purpose and you would have to write extra logic to fix it.

    In first case,

    1. Child can mutate item by mistake. You probably do not want that. This does not look like great abstraction.
    2. the code is much shorter and it does make sense, when the whole object item changes together and then extracting individual prop like prop1,prop2,prop3 do not make sense.
    Login or Signup to reply.
  2. I agree with Tushar Shai, that it depends on your use case.

    Also consider that when you pass the full object item={item}, the child component will not rerender when only a property, say prop1, of item has changed, whereas in your second proposition the Child-component would rerender and display the changed property.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search