Skip to main content

Avoid Code Duplication

DRY

Don't Repeat Yourself

Avoid code duplication for data objects

Objects
// Store the common props in an object
const common = {
prop1: 'prop1',
prop2: 'prop2',
};

const custom1 = {
...common, // 👈 spread the contents of common object
prop2: 'Prop: 2', // 👈 override
prop3: 'prop3', // 👈 Add new properties
prop4: () => console.log(this.prop2), // 👈 Add new
};
Arrays
const commonArr = ['prop1', 'prop2'];

// spread the common 👇 👇 Add new prop
const customArr = [...commonArr, 'prop3'];

Avoid code duplication for logic (functional code)

Extract and split everything up to an extent where we can't split it anymore, We'll have separated every step, every single work neatly into separate functions well organized in separate files and folders. If we need any piece of logic or work to be done again in some other place, we can re-use the existing code.

Avoid code duplication in UI code

Sort (Asc/Desc) Button | Everything is duplicate 💩💩💩
{
sort ? (
sort == 'asc' ? (
<button onClick={() => sortData('asc')}>
<span>Sort</span>
<icon>Ascending</icon>
</button>
) : (
<button onClick={() => sortData('desc')}>
<span>Sort</span>
<icon>Descending</icon>
</button>
)
) : null;
}
Sort (Asc/Desc) Button | Simplify ✅
<button onClick={() => sortData(sort)}>
<span>Sort</span>
{/* Only the icon needs to change */}
{sort ? sort === 'asc' ? <icon>Ascending</icon> : <icon>Descending</icon> : null}
</button>
Don't overuse ternary conditions

It is okay to use ternary conditions in UI code up to 1 or 2 levels at most, writing more than that makes it ugly and hard to read. it should be refactored and simplified.