Clean Code + Tips For React

Mahdia Aliyya
4 min readApr 5, 2021

Have you ever find yourself forgetting what you just code? Wondering “what is this line of code for?” Uh oh.. it might be a sign that your code is not clean. The idea of Clean Code is to write a clear, concise, effective code so that everyone in the team— not only you, can understand it easily.

Worry not! These are some guides on how to have a ✨ Clean Code ✨

So How do You Make Your Code “Clean”?

First of All, Follow Standard Conventions — Be Consistent

Usually, every coding language has its own preferable coding convention. This includes naming rules, whitespace, programming principles, etc. Try to Google it then always refer to them. For JavaScript, you can refer to this guide. While React has additional suggestions on file structure here.

If there are no conventions you can find — or there’s a lot of different ones, you can pick one that suits you. This has to be the guide for your whole project, and everyone in the team should follow. The key is to be consistent.

Set Clear, Descriptive Names

Whether it be a function, a variable, or a file name, please, do yourself and your team a favor by defining it clearly! The name should give people a clue on what it is and what it does. Here are some examples of bad naming:

Use meaningful names.

// nope
const [values, setValues] = React.useState({
name: '',
username: '',
email: ''
});
// ok
const [dataSiswa, setDataSiswa] = React.useState({
name: '',
username: '',
email: ''
});

Boolean variables. Start with “is”, “has”, or “should”

// nope
const siswa = true;
// ok
const isSiswa = true;

Function names. Describe what they do

// nope
const foo () => { ... };
// ok
const submitData () => { ... };

One Function, One Responsibility!

When you need to have a complicated function, that has some steps in it or a couple of subtasks, try splitting it into different functions — or components. So, instead of fitting everything into a single function, try to make it like this:

function Card(props) {
return (
<div>
<h2>{props.title}</h2>
{props.desc && <p>{props.desc}<p>}
</div>
)};

function CardList(props) {
const dataSekolah = props.data;
const listSekolah = dataSekolah.map((sekolah) =>
<Card title={sekolah.name} desc={sekolah.desc} />
);
return (
<div>
{listSekolah}
</div>
);
}

This way, your code is more readable and understandable. You would know what it is doing cause the functions explain themselves!

Look For Patterns, Don’t Repeat Yourself

If you find yourself coding the same thing over in places, make it a function that can be reused. Components

For example, I have this specific back button that is shown on multiple pages. Instead of declaring and styling the button on every single page, I’d rather create a separate BackButton component. Then, reuse that component on those pages.

// BackButton.js
const BackButton = (props) => {
return (
<StyledButton onClick= {(e) => props.handleClick(e)}>
<img src={BackIcon} />
Kembali
</StyledButton>
)
}

export default BackButton;

This will not only make your code simpler but also help you manage your components’ consistency and maintainability.

Comment Only When Its Necessary

Don’t write redundant comments. Don’t comment on every single line. The code should be clear enough that you don’t need any more explanations. Here’s an example:

// nope
const values = []; // data User;
// ok
const dataUser = [];

Error Handling

Things don’t always work smoothly. But having an error handler will make it easier for us to anticipate, locate, and fix problems. This is one of the examples from Riku Rouvila on handling errors when fetching data.

const Example = () => {
const { data, error, isLoaded } = useApiRequest(
"https://jsonplaceholder.typicode.com/todos"
);

if (error !== null) {
return <div>Error: {error.message}</div>;
}
if (!isLoaded) {
return <div>Loading...</div>;
}
return (
<div>
{data.map(item => (
<div>{item.id}</div>
))}
</div>
);
};

Other “crumbs” that make your code dirty

Notice if your code still has:

  • unused import
  • unused variables and function
  • commented-out line of codes

Now get rid of them.

More Tips For A Cleaner Code in React Project

Conditional Rendering

  • Use && Operator → use if you need to render a component only when the condition is true, and render nothing when false

Bad example:

const Button = (props) => { return (  <StyledButton>    <>{props.withIcon ? <StyledIcon src={props.src} /> : null </>}    {props.children}  </StyledButton>  )}export default Button;

Good example:

const Button = (props) => {  return (    <StyledButton>       {props.withIcon && <StyledIcon src={props.src}/>}       {props.children}    </StyledButton>  )}export default Button;
  • Use ternary operator → if you need to render one thing when a condition is true and render a different thing when the condition is false

Bad example:

const loginOrProfile = (auth) => {
return (
<div>
{auth.isAuthenticated && <p>Hello, {auth.name} !</p>}
{!auth.isAuthenticated &&
<div>
<p>Please Log In</p>
<button onClick={handleClick}>
Login
</button>
</div>
})}
</div>
)}
};

Good example:

const loginOrProfile = (auth) => {
return (
<div>
{auth.isAuthenticated ? (
<p>Hello, {auth.name} !</p>
) : (
<div>
<p>Please Log In</p>
<button onClick={handleClick}>
Login
</button>
</div>
)}
</div>
)}
};

For more examples on Clean Code and Javascript or React best practices, please check the references I put at the end of this article. Hope this helps!

--

--