JC
Jeremy "JC" Ashley
react development

Clean Code in React: 5 Tips and Techniques

Clean Code in React: 5 Tips and Techniques
3 min read
#react development

ReactJS is renowned for building scalable and performant applications. Whether you're working on a large or small project, focusing on code quality, readability, maintainability, and scalability is essential.

Good code quality not only makes your codebase robust but also reduces the number of PR comments from your teammates. And who doesn't appreciate a "Looks Good To Me" (LGTM) comment?

These tips will help you write maintainable, scalable, and readable code. Basic familiarity with React is recommended.

1. Use Constants

In JavaScript, constants declared with the const keyword prevent re-declaration of the same value. Constants are ideal for storing API keys, URLs, and content strings, improving scalability, readability, and internationalization (i18n).

Avoid hard-coding strings in your components. Isolate UI, data, and content layers by using constants.

// constants.js or en.js
const MESSAGES = { 
    HEADING: 'Welcome to the website',
    ENTER_YOUR_NAME: 'Enter your name',
    HOME: {
        HEADING: 'Welcome to the home page'
    }
};

Object.freeze(MESSAGES);

export default MESSAGES;

// Using constants.js in a component
import MESSAGES from '../constants/constants';

const Home = () => {
    return (
        <h1>{MESSAGES.HEADING}</h1>
    );
}

export default Home;

2. Use Helpers / Utils

Identify parts of the code that can be turned into independent utilities or helpers. This promotes the Single Responsibility Principle and enhances code reusability.

// dateUtils.js : Separate utility file for reusability

export function formatDate(date) {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(date).toLocaleDateString(undefined, options);
}

// Updated Blog component using the util
import React from 'react';
import { formatDate } from './dateUtils'; 

const Blog = ({ title, content, date }) => {
    return (
        <div>
            <h2>{title}</h2>
            <p>{content}</p>
            <p>Published on: {formatDate(date)}</p>
        </div>
    );
}

export default Blog;

3. Learn How to Use Props

Consistently consume props in your components for better readability and maintainability. Destructuring props enhances code clarity.


// Destructuring props in the component definition
const Input = ({ type, placeholder, name, onChange }) => {
    return (
        <input 
            type={type} 
            placeholder={placeholder} 
            name={name} 
            className="block p-2 my-2 text-black" 
            onChange={onChange}
        />
    );
}

export default Input;

4. Have One File for Each Component

Adopt the single responsibility principle by maintaining one file per component. This promotes cleaner and more maintainable code.


// Input.jsx
import React from 'react';

const Input = ({ type, placeholder, name, onChange }) => {
    return (
        <input 
            type={type} 
            placeholder={placeholder} 
            name={name} 
            className="block p-2 my-2 text-black" 
            onChange={onChange}
        />
    );
}

export default Input;

// Icon.jsx
import React from 'react';

const Icon = ({ type, url }) => {
    return <img src={url} alt={type} />;
}

export default Icon;

5. Use lazy() and Suspense()

Use lazy() to load components on demand and Suspense() to handle loading states.


import React, { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

const App = () => (
    <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
    </Suspense>
);

export default App;

Conclusion:

We've covered various tips for improving your React code:

Following DRY and Single Responsibility principles Loading data progressively Enhancing readability and developer experience Avoiding bugs during development Improving performance 🚀

PS

  • These are just some tips I wanted to pass on from my time working the past 2 years with React. Shout out to Mo for point 5 I learned this during my time with iServiceWeb
  • If you have any questions or comments, please reach out to me on LinkedIn (don't hesitate if you see something wrong)