DEV Community

Cover image for 7 Tips for Clean React TypeScript Code you Must Know 🧹✨
Tapajyoti Bose
Tapajyoti Bose

Posted on • Updated on

7 Tips for Clean React TypeScript Code you Must Know 🧹✨

Clean code isn't code that just works. It refers to neatly organized code which is easy to read, simple to understand and a piece of cake to maintain.

Let's take a look at some of the best practices for clean code in React, which can take the ease of maintaining your code to the moon! 🚀🌕

1. Provide explicit types for all values

Quite often while using TypeScript a lot of people skip out on providing explicit types for values, thus missing out on the true benefit TypeScript has to offer. Often these can be seen in code-base:

Bad Example 01:

const Component = ({ children }: any) => {
  // ...
};
Enter fullscreen mode Exit fullscreen mode

Bad Example 02:

const Component = ({ children }: object) => {
  // ...
};
Enter fullscreen mode Exit fullscreen mode

Instead using a properly defined interface would make your life so much easier, with the editor providing you accurate suggestions.

Good Example:

import { ReactNode } from "react";

interface ComponentProps {
  children: ReactNode;
}

const Component = ({ children }: ComponentProps) => {
  // ...
};
Enter fullscreen mode Exit fullscreen mode

2. Take the previous state into account while updating the state

It is always advisable to set state as a function of the previous state if the new state relies on the previous state. React state updates can be batched, and not writing your updates this way can lead to unexpected results.

Bad Example:

import React, { useState } from "react";

export const App = () => {
  const [isDisabled, setIsDisabled] = useState(false);

  const toggleButton = () => {
    setIsDisabled(!isDisabled);
  };

  // here toggling twice will yeild the same result
  // as toggling once
  const toggleButtonTwice = () => {
    toggleButton();
    toggleButton();
  };

  return (
    <div>
      <button disabled={isDisabled}>
        I'm {isDisabled ? "disabled" : "enabled"}
      </button>
      <button onClick={toggleButton}>
        Toggle button state
      </button>
      <button onClick={toggleButtonTwice}>
        Toggle button state 2 times
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Good example:

import React, { useState } from "react";

export const App = () => {
  const [isDisabled, setIsDisabled] = useState(false);

  const toggleButton = () => {
    setIsDisabled((isDisabled) => !isDisabled);
  };

  const toggleButtonTwice = () => {
    toggleButton();
    toggleButton();
  };

  return (
    <div>
      <button disabled={isDisabled}>
        I'm {isDisabled ? "disabled" : "enabled"}
      </button>
      <button onClick={toggleButton}>
        Toggle button state
      </button>
      <button onClick={toggleButtonTwice}>
        Toggle button state 2 times
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

3. Keep your files lean & clean

Keeping your files atomic and lean makes debugging, maintaining, and even finding the files a walk in the park!

Bad Example:

// src/App.tsx
export default function App() {
  const posts = [
    {
      id: 1,
      title: "How to write clean react code",
    },
    {
      id: 2,
      title: "Eat, sleep, code, repeat",
    },
  ];

  return (
    <main>
      <nav>
        <h1>App</h1>
      </nav>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            {post.title}
          </li>
        ))}
      </ul>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

Good Example:

// src/App.tsx
export default function App() {
  return (
    <main>
      <Navigation title="App" />
      <Posts />
    </main>
  );
}

// src/components/Navigation.tsx
interface NavigationProps {
  title: string;
}

export default function Navigation({ title }: NavigationProps) {
  return (
    <nav>
      <h1>{title}</h1>
    </nav>
  );
}

// src/components/Posts.tsx
export default function Posts() {
  const posts = [
    {
      id: 1,
      title: "How to write clean react code",
    },
    {
      id: 2,
      title: "Eat, sleep, code, repeat",
    },
  ];

  return (
    <ul>
      {posts.map((post) => (
        <Post key={post.id} title={post.title} />
      ))}
    </ul>
  );
}

// src/components/Post.tsx
interface PostProps {
  title: string;
}

export default function Post({ title }: PostProps) {
  return <li>{title}</li>;
}
Enter fullscreen mode Exit fullscreen mode

4. Use Enums or Constant Objects for values with multiple states

The process of managing variables that can take multiple states can be eased a lot by using Enums or Constant Objects.

Bad Example:

import React, { useState } from "react";

export const App = () => {
  const [status, setStatus] = useState("Pending");

  return (
    <div>
      <p>{status}</p>
      <button onClick={() => setStatus("Pending")}>
        Pending
      </button>
      <button onClick={() => setStatus("Success")}>
        Success
      </button>
      <button onClick={() => setStatus("Error")}>
        Error
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Good Example:

import React, { useState } from "react";

enum Status {
  Pending = "Pending",
  Success = "Success",
  Error = "Error",
}
// OR
// const Status = {
//   Pending: "Pending",
//   Success: "Success",
//   Error: "Error",
// } as const;

export const App = () => {
  const [status, setStatus] = useState(Status.Pending);

  return (
    <div>
      <p>{status}</p>
      <button onClick={() => setStatus(Status.Pending)}>
        Pending
      </button>
      <button onClick={() => setStatus(Status.Success)}>
        Success
      </button>
      <button onClick={() => setStatus(Status.Error)}>
        Error
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

5. Use TS-free TSX as much as possible

How can TSX be TS-free? 🤔

Relax, we are talking only about the Markup part NOT the entire component. Keeping it function-free makes the component easier to understand.

Bad Example:

const App = () => {
  return (
    <div>
      <button
        onClick={() => {
          // ...
        }}
      >
        Toggle Dark Mode
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Good Example:

const App = () => {
  const handleDarkModeToggle = () => {
    // ...
  };

  return (
    <div>
      <button onClick={handleDarkModeToggle}>
        Toggle Dark Mode
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

NOTE: If the logic is a one-liner, then using it in the TSX is quite acceptable.

6. Elegantly Conditionally Rendering Elements

Conditionally rendering elements is one of the most common tasks in React, thus using clean conditionals is a necessity.

Bad Example:

const App = () => {
  const [isTextShown, setIsTextShown] = useState(false);

  const handleToggleText = () => {
    setIsTextShown((isTextShown) => !isTextShown);
  };

  return (
    <div>
      {isTextShown ? <p>Now You See Me</p> : null}

      {isTextShown && <p>`isTextShown` is true</p>}
      {!isTextShown && <p>`isTextShown` is false</p>}

      <button onClick={handleToggleText}>Toggle</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Good Example:

const App = () => {
  const [isTextShown, setIsTextShown] = useState(false);

  const handleToggleText = () => {
    setIsTextShown((isTextShown) => !isTextShown);
  };

  return (
    <div>
      {isTextShown && <p>Now You See Me</p>}

      {isTextShown ? (
        <p>`isTextShown` is true</p>
      ) : (
        <p>`isTextShown` is false</p>
      )}

      <button onClick={handleToggleText}>Toggle</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

7. Use JSX shorthands

Boolean Props

A truthy prop can be provided to a component with just the prop name without a value like this: truthyProp. Writing it like truthyProp={true} is unnecessary.

Bad Example:

interface TextFieldProps {
  fullWidth: boolean;
}

const TextField = ({ fullWidth }: TextFieldProps) => {
  // ...
};

const App = () => {
  return <TextField fullWidth={true} />;
};
Enter fullscreen mode Exit fullscreen mode

Good Example:

interface TextFieldProps {
  fullWidth: boolean;
}

const TextField = ({ fullWidth }: TextFieldProps) => {
  // ...
};

const App = () => {
  return <TextField fullWidth />;
};
Enter fullscreen mode Exit fullscreen mode

String Props

A String Prop value can be provided in double-quotes without the use of curly braces or backticks.

Bad example:

interface AvatarProps {
  username: string;
}

const Avatar = ({ username }: AvatarProps) => {
  // ...
};

const Profile = () => {
  return <Avatar username={"John Wick"} />;
};
Enter fullscreen mode Exit fullscreen mode

Good example:

interface AvatarProps {
  username: string;
}

const Avatar = ({ username }: AvatarProps) => {
  // ...
};

const Profile = () => {
  return <Avatar username="John Wick" />;
};
Enter fullscreen mode Exit fullscreen mode

Undefined Props

Just like basic TypeScript/JavaScript, if a prop is not provided a value, it will be undefined.

Bad Example:

interface AvatarProps {
  username?: string;
}

const Avatar = ({ username }: AvatarProps) => {
  // ...
};

const Profile = () => {
  return <Avatar username={undefined} />;
};
Enter fullscreen mode Exit fullscreen mode

Good Example:

interface AvatarProps {
  username?: string;
  // OR `username: string | undefined`
}

const Avatar = ({ username }: AvatarProps) => {
  // ...
};

const Profile = () => {
  return <Avatar />;
};
Enter fullscreen mode Exit fullscreen mode

Now you too know how to write clean TSX!

victory-dance

Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

Follow me on Instagram to check out what I am up to recently.

Follow my blogs for Weekly new Tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

Top comments (23)

Collapse
 
loucyx profile image
Lou Cyx

A few things:

1. Provide explicit types for all values

I agree, but I would suggest you use PropsWithChildren if your component will have children. That type is provided by React and extends properties you have adding children as an optional property of type ReactNode:

import { PropsWithChildren } from "react";

const Component = ({
    disabled = false,
    children,
}: PropsWithChildren<{ disabled?: boolean }>) => {
    // ...
};
Enter fullscreen mode Exit fullscreen mode

Even if you only want to have children (which would be weird, because then why is that a component in the first place, then), you should type it as optional:

type ComponentProps = {
    children?: ReactNode;
};
Enter fullscreen mode Exit fullscreen mode

One extra tip, if you're just wrapping a native element and adding some props to it, you can get the types of said element:

const Component = ({
    customProp = "foo",
    ...props
}: JSX.IntrinsicElements["div"] & { customProp?: string }) => (
    <div data-custom-prop={customProp} {...props} />
);
Enter fullscreen mode Exit fullscreen mode

That will make Component have all the properties of a div, and add your custom props on top of it 😊

2. Take the previous state into account while updating the state

The toggleButtonTwice example shouldn't be solved by using the callback of setState, but should instead be addressed as a problem and fixed. If you have a boolean that you're toggling twice, then you're effectively just keeping it as it is:

!!true === true;
Enter fullscreen mode Exit fullscreen mode

And I know is "just an example", but the thing is that the callback in setState should be used mainly for async stuff in which you can't know the value beforehand. If you do know the value, you should just set it. An example for this:

// What you should avoid:
setState(state => state + 1);
setState(state => state + 1);
setState(state => state + 1);

// What you should do:
setState(state + 3);

// Or if you don't know the amount being added:
setState(state => state + valueA);
setState(state => state + valueB);
setState(state => state + valueC);

// You can do something like this:
let total = state;
total += valueA;
total += valueB;
total += valueC;
setState(total);

// Or just this:
setState(state + valueA + valueB + valueC);
Enter fullscreen mode Exit fullscreen mode

The important thing is to avoid calling the state setter constantly with callbacks when you can call it once with the final state you want. Callbacks are only good when is really not possible for you to know the current state when setting the new one (like in async scenarios).

3. Keep your files lean & clean

I agree with you here, but we shouldn't overdo it either. Having a Posts component that will only render a list of posts isn't great because the component by itself is useless. The idea of doing this kind of separation of concerns is also to keep every part useful on its own. One other "rule" you should keep in mind if that if your component isn't adding anything to the native element (like a className), then you can just use the native element instead:

// src/data/posts.ts
const posts = [
    {
        id: 1,
        title: "How to write clean react code",
    },
    {
        id: 2,
        title: "Eat, sleep, code, repeat",
    },
];

// src/components/Heading1.tsx
export const Heading1 = ({
    className,
    ...props
}: JSX.IntrinsicElements["h1"]) => (
    <h1 className={`heading1 ${className ?? ""}`} {...props} />
);

// src/components/Navigation.tsx
export const Navigation = ({
    className,
    ...props
}: JSX.IntrinsicElements["nav"]) => (
    <nav className={`navigation ${className ?? ""}`} {...props} />
);

// src/components/Posts.tsx
export const Posts = ({ className, ...props }: JSX.IntrinsicElements["ul"]) => (
    <ul className={`posts ${className ?? ""}`} {...props} />
);

// src/components/Post.tsx
export const Post = ({ className, ...props }: JSX.IntrinsicElements["li"]) => (
    <li className={`post ${className ?? ""}`} {...props} />
);

// src/App.tsx
export const App = () => (
    <main>
        <Navigation>
            <Heading1>App</Heading1>
        </Navigation>
        <Posts>
            {posts.map(({ id, title }) => (
                <Post key={id}>{title}</Post>
            ))}
        </Posts>
    </main>
);
Enter fullscreen mode Exit fullscreen mode

You might notice that I added classNames to everything, and that is to justify their existence a little, because without that, I would just...

export const App = () => (
    <main>
        <nav>
            <h1>App</h1>
        </nav>
        <ul>
            {posts.map(({ id, title }) => (
                <li key={id}>{title}</li>
            ))}
        </ul>
    </main>
);
Enter fullscreen mode Exit fullscreen mode

4. Use Enums or Constant Objects for values with multiple states

If you have complete control over those states and you're not planning on giving other devs those values, that's ok ... if not then it becomes kinda cumbersome because they need to import your component and your enum/object just to set a few strings. What you can do is to have a type like this:

type Status = "pending" | "success" | "error";
Enter fullscreen mode Exit fullscreen mode

And then use that for your state:

const [status, setStatus] = useState<Status>("pending");
Enter fullscreen mode Exit fullscreen mode

And you can also use it as the type for properties and the best thing about it is that it will provide auto-completion and suggestions (which is better than just using string for it). If you want to have both a good DX and keep the object for your internal use, what you can do is:

const StatusMap = {
    pending: "pending",
    success: "success",
    error: "error",
} as const;

type Status = keyof typeof StatusMap; // "pending" | "success" | "error" is inferred
Enter fullscreen mode Exit fullscreen mode

And if you update StatusMap, Status will be updated automatically 🎉

6. Elegantly Conditionally Rendering Elements

Short-circuit is not elegant, is just looking for bugs like rendering falsy values to the DOM. Ideally you should always use ternaries, and if you don't like them, you can always use something like a when function:

const when = (condition, render) => (condition ? render() : null);
Enter fullscreen mode Exit fullscreen mode

And then just:

const App = () => {
    const [isTextShown, setIsTextShown] = useState(false);

    return (
        <div>
            {when(isTextShown, () => (
                <p>Now You See Me</p>
            ))}
            <p>`isTextShown` is {isTextShown.toString()}</p>
            <button onClick={() => setIsTextShown(!isTextShown)}>Toggle</button>
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

Tho I would personally just stick with ternaries:

const App = () => {
    const [isTextShown, setIsTextShown] = useState(false);

    return (
        <div>
            {isTextShown ? <p>Now You See Me</p> : undefined}
            <p>`isTextShown` is {isTextShown.toString()}</p>
            <button onClick={() => setIsTextShown(!isTextShown)}>Toggle</button>
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

7. Use JSX shorthands

100% this, but you forgot that you need to make the boolean properties optional to work as expected, because if not then we need to pass prop={false} instead of just omitting it which isn't ideal. Also is good to set the default value to false so inside the function fullWidth is always a boolean, instead of boolean | undefined:

type TextFieldProps = {
    fullWidth?: boolean;
};

const TextField = ({ fullWidth = false }: TextFieldProps) => {};

const App = () => <TextField fullWidth />;
Enter fullscreen mode Exit fullscreen mode

I didn't forget about 5, I just think that one is more an stylistic choice, I tend to keep my functions small so inlining them is not biggie, but some folks might want to move them away from JSX for readability and that's ok.

Cheers!

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto

Well remembered, the setter of useState is already memoised, no need to wrap in a usrCallback.

Thanks for the article @ruppysuppy and the tips @lukeshiru

Collapse
 
silverium profile image
Soldeplata Saketos

For point #7 I would even add:
"Don't set unneeded falsey values, as they render as attributes in HTML"
instead of

type TextFieldProps = {
    fullWidth?: boolean;
};

const TextField = ({ fullWidth = false }: TextFieldProps) => {};

const App = () => <TextField fullWidth />;
Enter fullscreen mode Exit fullscreen mode

which would eventually render into:

<input full-width="false"/>
Enter fullscreen mode Exit fullscreen mode

leave it as undefined:

type TextFieldProps = {
    fullWidth?: boolean;
};

const TextField = ({ fullWidth }: TextFieldProps) => {};

const App = () => <TextField fullWidth />;
Enter fullscreen mode Exit fullscreen mode

so it can skip the attribute in the HTML

Collapse
 
anatooly profile image
Antony Bash

Thank, great solutions.

Collapse
 
lico profile image
SeongKuk Han • Edited

Agree with third one. in some cases(when it's over used), that makes a project too complicated.

Collapse
 
jt3k profile image
Andrey Gurtovoy

damn good answer, thanks! now I have an argument to explain my actions in the code. if I had just read the article, then there would be less such argumentation.

Collapse
 
yusub profile image
Yusub Yacob

you are the best man .

Collapse
 
mrcaidev profile image
Yuwang Cai

Great article!
A little complain about conditional rendering in React: Even though ternary expression is the best solution I know, these brackets still makes my code looking like a mess. And I really love the v-if directive in vue, which surprises me a lot at first glance.

Collapse
 
brense profile image
Rense Bakker

You can use this as a type for your components that use children:

function My component({children, otherProp}:React.PropsWithChildren<{otherProp:string}>){
  // ...
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
zyabxwcd profile image
Akash • Edited

I am in love with the variable name 'truthyProp' lol
I think one of the weird thing Software Developers develop over time is admiration towards amazing variable names. Whenever I name one or see one, I get so happy and obsessed over it XD. It gives such a pleasurable feeling haha

Collapse
 
elijahtrillionz profile image
Elijah Trillionz

A really good writeup.
Thanks for this article.
I like the fact that you made bad examples and good examples, so I can see the "me" now, and the "me" I ought to be 😁.

Collapse
 
majscript profile image
MajScript

Nice!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Dope list thanks for creating it!

Collapse
 
makodev profile image
mako

This is really nice

Collapse
 
akshaysrepo profile image
Akshay S

`import { ReactNode ,FC } from "react";

interface ComponentProps {
children: ReactNode;
}

const Component:FC = ({ children }) => {
// ...
};`

This seems more sensible

Collapse
 
loucyx profile image
Lou Cyx

I used to use FC as well, but React is doing work to "deprecate" that, so the next sensible approach is to use PropsWithChildren if you want a component with children on it, or just type the props directly if your component doesn't have children.

Collapse
 
klajdi44 profile image
Klajdi Ajdini

Fenomenal tips @lukeshiru

Collapse
 
lifeiscontent profile image
Aaron Reisman

fwiw, you shouldn't be using interfaces unless you want to enhance a type.

e.g.:

interface Example {}

interface Example {
    foo: 'bar';
}

interface Example {
    baz: 'qux';
}

type Foo = Example['foo'];
type Baz = Example['baz'];


// @ts-expect-error TExample is defined
type TExample = {}

// @ts-expect-error TExample cannot be redefined
type TExample = {
    foo: 'bar';
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wilmela profile image
Wilmela

Very well written, thanks. However on point no. 3. When you have a simple component you won't be using else where, doesn't it make sense creating it in the same file instead of a whole new file?

Collapse
 
mrdulin profile image
official_dulin

Several tips are naive.

Collapse
 
aradwan20 profile image
Ahmed Radwan

Good one!

Collapse
 
itminhnhut profile image
itminhnhut • Edited
import { FC, ReactNode } from 'react';

interface ComponentProps {
    children: ReactNode;
}
const LeadsList: FC<ComponentProps> = () => {}

my opinion.
Enter fullscreen mode Exit fullscreen mode