Clean Code React Project
- Use Ternary Operators
Let’s say you want to show a particular user’s details based on role.
Bad
const { role } = user;
if(role === USER) {
return <SuperUser />
} else {
return <SubUser />
}
Good
const { role } = user;
return role === USER ? <SuperUser /> : <SubUser />
2. Take Advantage of Object Literals
Object literals can help make our code more readable. Let’s say you want to show three types of users based on their role. You can’t use ternary because the number of options is greater than two.
Bad
const {role} = user
switch(role){
case ADMIN:
return <AdminUser />
case STUDENT:
return <StudentUser />
case USER:
return <NormalUser />
}
GOOD
const {role} = user
const components = {
ADMIN: AdminUser,
EMPLOYEE: StudentUser,
STUDENT: NormalUser
};
const Component = components[role];
return <Componenent />;
3. Use Fragments
Always use Fragment
over Div
. It keeps the code clean and is also beneficial for performance because one less node is created in the virtual DOM.
Bad
return (
<div>
<Component1 />
<Component2 />
<Component3 />
</div>
)
Good
return (
<>
<Component1 />
<Component2 />
<Component3 />
</>
)
4. String Props Don’t Need Curly Braces
When passing string props to a children component.
Bad
return(
<Navbar title={"My Special App"} />
)
Good
return(
<Navbar title="My Special App" />
)
5. Use Implicit return
Use the JavaScript feature of implicit return
to write beautiful code. Let’s say your function does a simple calculation and returns the result.
Bad
const add = (a, b) => {
return a + b;
}
Good
const add = (a, b) => a + b;
Thank You