DEV Community

Cover image for 🧼 How to Write Clean React Code
Leap ChanVuthy
Leap ChanVuthy

Posted on

🧼 How to Write Clean React Code

Writing clean code in React is not just about making it work—it's about making it readable, maintainable, and scalable. Whether you’re building a simple to-do app or a large-scale application, following clean code principles will make your life (and your team’s) much easier.

Here are some practical tips to help you write clean React code 👇

  1. 📁 Organize Your Folder Structure Structure your project in a scalable way. Avoid dumping all files in one folder.

Bad:

/src
App.js
index.js
Component1.js
Component2.js

Good :


/src
/components
/Navbar
Navbar.jsx
Navbar.module.css
/Button
Button.jsx
/pages
Home.jsx
App.jsx
index.js

  1. 🧩 Use Functional Components & Hooks Prefer functional components with hooks over class components.
// ✅ Clean
function Welcome({ name }) {
  return <h1>Hello, {name}!</h1>;
}
Enter fullscreen mode Exit fullscreen mode
  1. 📦 Break Components into Smaller Pieces Keep components small and focused on one task. If a component is doing too much, break it into smaller ones.
// ❌ Bad
const Dashboard = () => {
  // fetching, rendering UI, handling logic... all in one
};

// ✅ Good
// Dashboard.jsx → uses <UserList />, <StatsPanel />, etc.
Enter fullscreen mode Exit fullscreen mode
  1. 🧹 Clean Up useEffect Always clean up side effects to avoid memory leaks.
useEffect(() => {
  const interval = setInterval(() => {
    console.log("Running...");
  }, 1000);

  return () => clearInterval(interval); // ✅ cleanup
}, []);

Enter fullscreen mode Exit fullscreen mode
  1. 🧪 Write Reusable Hooks Extract reusable logic into custom hooks.
// useToggle.js
import { useState } from 'react';

export function useToggle(initialValue = false) {
  const [state, setState] = useState(initialValue);
  const toggle = () => setState(prev => !prev);
  return [state, toggle];
}
Enter fullscreen mode Exit fullscreen mode

🚀 Final Thoughts
Clean React code is:

Easy to read 👓

Easy to reuse ♻️

Easy to test 🧪

Easy to maintain 🛠️

You don’t need to be perfect—just aim for improvement step by step. Happy coding! 🎉

Top comments (0)