Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a function and a stateless component?

The two examples below are apparently resulting in the exact same code.

Example 1 (React child):

const Child = ({ item: { startedAt, count } }) => (
  <div>
    <div>{startedAt}</div>
    <div>{count}</div>
  </div>
)

const Parent = items => {
  return (
    <div>
      {items.map((item, index) => (
        <Child key={item.id} item={item} />
      ))}
    </div>
  )
}

export default Parent

Example 2 (function child):

const child = ({ id, startedAt, count }) => (
  <div key={id}>
    <div>{startedAt}</div>
    <div>{count}</div>
  </div>
)

const Parent = items => {
  return <div>{items.map(child)}</div>
}

export default Parent

Why would one go with example 1, i.e. a React component? Are there any benefits over the function example?

like image 346
Fellow Stranger Avatar asked Jan 01 '23 20:01

Fellow Stranger


2 Answers

Actually, these 2 snippets of code are not completely equivalent:

The first example is creating a new (and unnecessary) function in every render (the one inside items.map that creates and returns the Child element), which can clutter the garbage collector. Therefore, the second example is not only more concise, it also performs better. So, I personally, would go with the second example.

Also, the second example won't nest an unnecessary call to React.createElement. Meaning that the map function will return something like:

[
  React.createElement('div', {key: items[0].key},
    React.createElement('div', null, items[0].startedAt),
    React.createElement('div', null, items[0].count)
  ),
  React.createElement('div', {key: items[1].key},
    React.createElement('div', null, items[1].startedAt),
    React.createElement('div', null, items[1].count)
  ),
  ...
]

The first example, on the other hand, does something like this:

[
  React.createElement(Child, {key: items[0].key}, items[0]),
  React.createElement(Child, {key: items[1].key}, items[1]),
  ...
]

It's also worth pointing out that the child function of your second example is actually a stateless functional component too. Whether you want to consume it calling the function directly or wrapping it though a React.createElement call is up to you, in this case I think that it makes more sense to call the function directly.

like image 92
Josep Avatar answered Jan 05 '23 05:01

Josep


The both are stateless react components. Your second example has also react child -Functional Components are stateless react components. This is more about code readability and this could be a syntactic sugar to render child components. You can inspect in dev tools as it will show them as React.CreateElement.

I would rather go for first example. It gives an clear manifestation there's an child component exists.

I hope this helps.

like image 37
Sakhi Mansoor Avatar answered Jan 05 '23 05:01

Sakhi Mansoor