This post was originally posted on my blog @ easy-code.blog
As React is the most popular web framework according to Stackoverflow survey for 2022 I would like to show you some code best practices to improve your coding.
Arrow Functions:
An arrow function is the compact alternative to function expression and can let your code be cleaner.
//Instead of doing that:
function addNumbers(x, y) {
return x + y;
}
// Better to use:
const addNumbers = (x, y) => x + y;
// With block body, explicit "return" needed
const addNumbers = (x, y) => {
return x + y;
}
Object destructuring assignment:
The destructuring assignment syntax is an expression that makes it possible to unpack properties from objects, into distinct variables.
var myData = {
date: new Date('2022-11-18T22:12:03.284Z'),
data: 'This is my data',
dataCounter: 42
}
const {date, data, dataCounter} = myData;
// Now your object is separate into distinct variables.
console.log(date, data, dataCounter);
Avoid "CSS-in-JS" or "Inline Styling" patterns:
"CSS-in-JS" or "Inline Styling" refers to a pattern where CSS is composed using JavaScript instead of defined in external files.
for example:
const myTitle = '{easy-code} blog'
const TitleText = <div style={{fontSize: 1em}}>{myTitle}</div>
Those patterns will makes your JSX code not clean and harder to maintenance, if you often find yourself writing code like this, better to export your styles into different css file. Doing this will allow you reuse your styling without duplicate your code and your component will be smaller and easily to understand and use.
For example:
const myTitle = '{easy-code} blog'
const TitleText = <div className='title'>{myTitle}</div>
The css should look like this:
.title {
font-size: 1em,
font-weight: bold;
}
Add Keys to the elements inside the array:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
for example:
const users = [{id: 1, name: ''}, {id: 1, name: ''}];
const IdxItems = <ul>{
users.map((user) =>
<li key={user.id}>{user.name}</li>
)}
</ul>;
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Therefore, use IDs from your data would be a good key choose.
But when you don't have stable IDs and unique so React will render your items correctly, you can use the item index as a key.
For example:
const users = [{name: ''}, {name: ''}];
const IdxItems = <ul>{
users.map((user, index) =>
<li key={index}>{user.name}</li>
)}
</ul>;
Be aware!
It is not recommended to use indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.
If youβre interested in learning more, you can find more details Here.
Always destructuring your Props
Using Props allow you component to reusable which will make your code clean. Therefore, again destructuring object come to help you.
const Header = ({title, iconSrc}) => {
return (
<div>
<h1>{title}</h1>
<img src={iconSrc}/>
</div>
);
}
Use equality (==) and avoid strict equality (===)
While you compare your objects, try avoiding the strict equality (===) operator as is could lead to misleading evaluation.
For example:
const result = '32' === 32 // false
const result = '32' == 32 // true
The reason is that the strict operator checks whether its two operands are equal, returning a Boolean result. The strict operator will return True only if the operands have the same type. Unlike the equality operator (==) which will compare the values without consider the operands type.
You can find another advantage to use equality (==) with objects.
For example, if you have some null object and you need to compare it to undefined object which most of the time handle with the same logic.
const obj1 = null;
const obj2 = undefined;
const result = obj1 === obj2 // false
const result = obj1 == obj2 // true
Now you can go and start coding better, hope you enjoy! ππ»
Happy Debugging π¨πΌβπ»π©βπ»
Top comments (2)
Agree to most of it, except the arrow functions always being the better option. Afaik the best practice is to use arrow functions in place of anonymous callbacks, but to make your named functions as actual function declarations, in order to avoid confusion with other const/let declarations:
Also the part about not using inline-styles seems a bit opinionated. Yes, when people put 100 inline-style declarations on the same line, thats horrible, but thats a different kind of problem, its not the inline-styles fault, but the developer! There are also very good css-in-js solutions out there like emotion/styled components that help and several good UI component libraries like @mui that offer built-in ways to do styling.
Btw, another best practice would be to not use
var
.Thanks for your feedback :)