Created
August 27, 2018 08:33
-
-
Save josemussa/5f4bc74d66493c035347b6120f12d4cf to your computer and use it in GitHub Desktop.
Avoid renderThing methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Avoid renderThing methods | |
If you’ve defined a custom method in your component that starts with the word render, chances are that should be its own component. As (Chris Biscardi)[https://mobile.twitter.com/chrisbiscardi/status/1004559213320814592] puts it, “[It] effectively means there’s enough complexity to be worth breaking down”. React’s smart about when to render or not render a component, so by splitting these out into their own components, you can help React do its job better. | |
```JS | |
// Instead of this | |
class Items extends React.Component { | |
renderItems ({ items }) { | |
return items.map(item => ( | |
<li key={item.id}> | |
{renderItem(item)} | |
</li> | |
)) | |
} | |
renderItem (item) { | |
return ( | |
<div> | |
{item.name} | |
</div> | |
) | |
} | |
render () { | |
return ( | |
<ul> | |
{renderItems(this.props) | |
</ul> | |
) | |
} | |
} | |
``` | |
```JS | |
// Do this | |
const ItemList = ({ items }) => | |
<ul> | |
{items.map(item => ( | |
<li key={item.id}> | |
<Item {...item} /> | |
</li> | |
)} | |
</ul> | |
const Item = ({ name }) => | |
<div>{item.name}</div> | |
class Items extends React.Component { | |
render () { | |
const { items } = this.props | |
return <ItemList items={items} /> | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment