DEV Community

Discussion on: Writing clean, reusable components in React (best practices)

Collapse
 
seandinan profile image
Sean Dinan

Very good write-up! One thing I would add in terms of reusability is render props. For example, if you have a generic button that renders a logo and a label, you can maximize reusability with a renderIcon prop.

const IconButton = ({ label, renderIcon, onClick }) => (
  <button onClick={onClick}>
    <span style={{ marginRight: '1.5rem' }}>
      {renderIcon(styles.buttonIcon)}
    </span>
    {label}
  </button>
)
Enter fullscreen mode Exit fullscreen mode
/* ...other component code */
<IconButton label="Save" renderIcon={(style) => <CheckIcon style={style}/>}/>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codewithshahan profile image
Programming with Shahan

Thanks for sharing. I tried my best to keep this article as simple as possible focusing purely on beginners.

There are more advanced concepts for reusable components in React. Most of the time, we use Hooks in React for building reusable comp. Actually,they were introduced as a way to write reusable and stateful logic in functional components without needing class components.

But I believe, beginners should understand the React fundamental concepts pretty clearly first before jumping into advanced topics. That is what the article is about.

Collapse
 
abhay_a_joshi profile image
Abhay Joshi

Thanks for writing this great article. As you mentioned this is focused for beginners, may be, title also can include that information.