DEV Community

Cover image for Best Practices for Writing Clean React Code
Amrita-padhy
Amrita-padhy

Posted on

Best Practices for Writing Clean React Code

Why is organizing and writing clean React Code important?

Clean code organization is important in React for practical reasons, as well as for its visual impact. A well-designed and well-organized codebase can be visually pleasing, making it easier to work with and understand.

Again, when the code is clean and well-organized, it's easier to see the relationships between different elements, understand how they fit together, and make changes as needed.

Here are some best practices to help you achieve that goal:

** Follow a Consistent Code Style:**
Establish a consistent code style for your project. You can use popular tools like ESLint and Prettier to enforce coding standards. This makes the codebase more readable and maintainable.

Component Organization:
Organize your project into a clear directory structure. Group related components, styles, and tests together. This will make it easier to find and update code.

Single Responsibility Principle (SRP):
Follow the SRP principle by ensuring that each component or function has one clear responsibility. This makes it easier to understand and test your code.

Use Functional Components:
React functional components with hooks are the recommended way of writing components. They make it easier to manage component state and lifecycle.

Avoid Complex Component Hierarchies:
Keep your component hierarchy as flat as possible. Complex nesting can make the code harder to follow and debug.

Reusable Components:
Create reusable components that can be used in multiple parts of your application. This reduces code duplication and simplifies maintenance.

Destructuring and Prop Spreading:
Use destructuring and prop spreading to make component props more readable. Instead of props.name, you can use { name }. Avoid spreading all props unless necessary.

State Management:
If your application needs state management beyond local component state, consider using state management libraries like Redux or React Context API. Keep your state logic centralized and separate from presentation components.

Use PureComponent or Memoization:
To improve performance, use React.memo or extend React.PureComponent for components that don't need to re-render on every prop change. This can prevent unnecessary rendering.

Comments and Documentation:
Add comments to explain complex logic or tricky parts of your code. Additionally, maintain documentation for your components and APIs, making it easier for other developers (or your future self) to understand the code.

Use stateless components
One should use stateless components whenever possible. Stateful components are more complex and harder to reason about. Stateless components are easier to reuse and compose since they only have to render based on the data passed to them through props. They are also easier to test since they don't have any internal state to manage.

Top comments (27)

Collapse
 
nmitic profile image
Nikola Mitic

Hey 👋 Hate to be that person. But I don't think this post actually can make people write better React code. People need an explanation of why and how doing the above will make our React code more clean.

Somebody mentioned the examples as well. Although not necessarily, even pseudo code can help.

Another thing, we should really challenge ourselves how much of the recommendations we share is truly a reflection of a real case scenario where such implementation can lead to better software and better user experience and how much of it is just a personal preference.

Rule of thumb, if you can't quantify or measure your clean code principles they are most likely your personal preference. Which is also valuable but it's prone to long and exhausting and never-ending discussions about what the clean code actually is.

In any way, I do agree with most, but I also do recognize that our personal preferences match.

Keep up with the good work 👏

Collapse
 
elsyng profile image
Ellis • Edited

Some explanation has been given. And I think with or without extensive explanation/etc, developers can still share their experiences and thoughts with each other, and it is very useful. It promotes thought and discussion. Me thinks :)

Collapse
 
mrmalik16 profile image
Sharjeel Faiq

Right.

Collapse
 
sergeypodgornyy profile image
Sergey Podgornyy

When writing about best practices, it would be more clear to have code examples 😉

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Ctrl + A, then Del. Then rename files to .svelte. 😄

Just joking around. Good tips.

Collapse
 
gweaths profile image
Grant Riordan

I agree with others. It would be good to get some context of:

  • Why it is best practice
  • Offer examples of good Vs bad
  • What are the benefits of each point you make (if there is any maybe also mention the drawbacks / constraints)

As a whole the article doesn't teach or offer any real value. A lot of the "advice" are blanket statements without any real help , teachings or guidance.

I'd perhaps take the feedback on board and add in additional content mentioned above.

Collapse
 
rajaerobinson profile image
Rajae Robinson

Great tips! I also recommend much of the same in this article.

Collapse
 
matek075 profile image
Matek

Nice content, just one small advice will be nice to include some small code snippets :-)

Collapse
 
bridgerbrowndev profile image
Bridger Brown

Are comments actually useful though or do they end up doing more harm in the long run? Creating functions, variables, etc. with descriptive names should do enough and require less maintenance. If you have comments and need to change things, now you need to change the names and the comments. I know this isn't a new take, and just goes back to the Clean Code book, but I thought I'd raise the point.

Collapse
 
thomas_kanzig profile image
Thomas Kanzig

Really good guide.
Thanks.

Collapse
 
olardev profile image
Oriade Yusuf

That's nice....

Collapse
 
marcitpro profile image
Marcitpro

I'm just learning programming, but this post is great

Collapse
 
antonkobelev profile image
AntonKobelev

Thanks!:) 👍

Collapse
 
voko profile image
Ko

Sometimes you need to write beautiful code. Sometimes it's more profitable to write dirty code.
They complement each other. It should be possible to combine both methods.
Blindly following beautiful practices leads to a dead end

Collapse
 
damian_cyrus profile image
Damian Cyrus

I hear others scream at "dirty code": "Technical debt!" Or "Stop! It's refactoring time!" And see the devs dance happy and the project manager is crying because the dirty code was a bad decission for the long run. ^^

Collapse
 
voko profile image
Ko

By saving time on unimportant details, you can pay more attention to the important ones.
With this method you will save time or be able to solve more complex problems.

My experience shows that if you don’t go to extremes and don’t hold yourself back with barriers, the work will be easier, the speed will be higher, the quality will be higher, and there will always be time for refactoring.

Collapse
 
amritapadhy profile image
Amrita-padhy

can u please explain me why is that so?

Collapse
 
deathcrafter profile image
Shaktijeet Sahoo

Sometimes you are just fed up with the project manager and just want to f him up in some way or the other.

Jokes apart, sometimes somethings don't work, and you have to go through some kind of work around to make it work, turning your code dirty (written not using best practices).

Unless the OP is a troll, I would guess that's what he's trying to say.

Collapse
 
mickaelbaye profile image
Mickaël B

This article is largely inspired by ChatGPT reponse (more than 90%). I just tried by tiping the title as prompt, I got almost the same response... What is the point to create a post about it ?

Collapse
 
elsyng profile image
Ellis

You can say that for a lot of things, and perhaps for the most articles on dev.to. Then what are you doing on dev.to? Just go to ChatGPT instead :o)

Collapse
 
mickaelbaye profile image
Mickaël B

I disagree. I think dev.to is a great community and I don't think most of the articles can't be generated only with ChatGPT or equivalent because people usually shared real life experience and opiniated recommandations. That's why people, including myself, are coming here. Also, there is nothing wrong using ChatGPT to create a post and I think it is actually tolerated if you at least be transparent about it... just sayin :o)

Collapse
 
elsyng profile image
Ellis

Avoid Complex Component Hierarchies:
-- Fully agreed, as flat as possible. Hierarchies we invent today often do not make sense tomorrow.

Destructuring and Prop Spreading:
-- I'd like to add: minimise the scope of a variable, and minimise the number of variables within a scope.

State Management:
-- I'd like to add: Think "component based programming". Keep everything local (meaning inside the component) and avoid global anything as much as possible, including: data storage, and styling.

Reusable components:
-- I'd like to add: try to make components completely independent of each other. They should not have co-dependencies. Changing one should not break the other. Except for the props of course: that's the contract and the signature of a component.

Collapse
 
shahrozahmd profile image
Shahroz Ahmed

Hey, let's say I have 2 components and I want to make a third component using those 2 components, is It also comes under Complex Component Hierarchies.