How To Reuse Code in React. Techniques that will help you share… | by Bohdan Balov | Feb, 2022

Techniques that will help you share React code in a right way

A bookstore
Image by Noémi Macavei-Katócz on Unsplash

You should already know this design principle — Don’t Repeat Yourself. Right? This sounds absolutely clear and reasonable: code duplications must be avoided. But where are boundaries? Should we avoid every code duplications we face? What is the minimal code size that should be made shared and reusable?

In this section, we are going to look for a balance. Because this is the main thing in the debates about reusability and supportability. Let’s start with a green light for sharing a piece of code.

And now you may ask how to recognize hasty abstractions and avoid them. You should look at that article by Kent C. Dodds for details. And there are my points from the top of my head.

const getIsUserOfType = curry((type, user) => user.type === type);const user = { id: '1', type: 'WRITER' };
getIsUserOfType('ADMIN', user); // false
getIsUserOfType('WRITER', user); // true
const getIsUserOfAdminType = getIsUserOfType('ADMIN');
const getIsUserOfWriterType = getIsUserOfType('WRITER');
getIsUserOfAdminType(user); // false
getIsUserOfAdminType(user); // true
  • Duplicated code that’s waiting for its time to be made universal and shared.

I don’t want to write a lot of words about React techniques to share code. Why? Just because there are a lot of articles on this topic! There are items you should pay attention to.

Leave a Comment