DEV Community

Cover image for 10 Must-Know Patterns for Writing Clean Code with React and TypeScript✨🛀

10 Must-Know Patterns for Writing Clean Code with React and TypeScript✨🛀

Alex Omeyer on February 04, 2022

React is a JavaScript library, and it is the most popular and industry-leading frontend development library today. JavaScript is a loosely typed l...
Collapse
 
peerreynders profile image
peerreynders • Edited

Bonus: Don’t use enum

Your "Do this" doesn't even compile because Successful, Failed, and Pending aren't even values yet.

Perhaps you were thinking

type Status = 'Successful' | 'Failed' | 'Pending';

function fetchData (status: Status): void {
    // some code.
}
Enter fullscreen mode Exit fullscreen mode

However the recommended pattern is more like this:

const STATUS = {
  Failed: -1,
  Pending: 0,
  Successful: 1,
} as const;

type Status = typeof STATUS[keyof typeof STATUS];

function fetchData (status: Status): void {
    // some code.
}

const someStatus = STATUS.Successful;
Enter fullscreen mode Exit fullscreen mode

Objects vs Enums

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
thewix profile image
TheWix

Not sure what you are getting at here that can't be said about any other language? What about a world class Typescript developer over the many poor JS or JQuery developers?

Typescript is not a silver bullet but it is certainly better than a massive untyped JS project. Doesn't matter how amazing your JQuery is, because you and your team are very likely not better than a compiler.

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
thewix profile image
TheWix

I dunno what 'Typescript' patterns you are referring to. Abusing or overusing interfaces is something I have seen in every language that has Java/C#-like interfaces. It is hard to know what bad code you have run into, but it sounds like your problem is with developers as opposed to Typescript itself.

Collapse
 
pengeszikra profile image
Peter Vivo

Imho, my react works I don't use any class component, just functional component, seems much easier.

Looks like this:

export const TypeOfProductButtonList:FC<{linkedList:IJoinedProduct[]}> = ({linkedList}) => (
  <>
    {linkedList.map(({product}) => <ProductButton product={product} />)}
  </>
)
Enter fullscreen mode Exit fullscreen mode

So I don't know why worst is the FC? Imho that is perfect if interface declared.

I started add typescript added our project, so actually whole JS code contain a few TS type definition - great help. Any way now, our project is state of JS - TS hybrid project, and works fine, even pipeline operator is works under TS.

Collapse
 
jaecktec profile image
Constantin

I agree but in your example you should use VFC since you don't have children

Collapse
 
pengeszikra profile image
Peter Vivo • Edited

I count in our working project (24k line JS/TS) contain only 4 times children use in component.

Collapse
 
develliot profile image
Develliot

All good stuff. I don't see anything wrong with using the FunctionComponent, in fact I would strongly advocate for it especially if you are building a FunctionComponent. In fact I would say use as many built in types as possible before creating your own.

I maintain a Typescript React component library and the biggest mistake I made was not originally using the built in types for all the html components and all their attributes that React gives you for free and just extending them. I was originally creating all custom types from scratch and getting issues reported about properties not working time and time again because I had forgotten something important.

React and it's types are maintained by hundreds of developers and it's silly not to trust many eyes on it vs our own.

Collapse
 
bennycode profile image
Benny Code

Why do you need PropTypes when coding with TypeScript? I would rather use React.FC and benefit from type-checking and autocomplete than not using it for the sake of PropTypes.

Collapse
 
milkywayrules profile image
Dio Ilham D

very opinionated.

Why would anyone still using class components nowadays, u should refactor to functional component as they stated better to not use class component anymore and use functional instead.

Collapse
 
mzbac profile image
Anchen

Not sure all the patterns mentioned as valid for clean code. Very opinionated.

Collapse
 
yevhenoksenchuk profile image
Yevhen
  1. We dont use class components last 2 years. 2 enum isnt for declare types. It useful in other cases
  2. Dont use FC, some of cases doesnt work without FC, and generic types to declare props. Ts knows about children as default, we dont need declare it
Collapse
 
glowkeeper profile image
Steve Huckle • Edited

If you want 'private', use closures. Something like:

const friends = () => {
  fetchProfileByID () {} // this probably gets called at initialisation by useEffect

  function render() {
    return // jsx blob
  }

  return { render }
}

const myFriends = friends
myFriends.render()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jbaez profile image
jbaez

Good article, I agree with most points.
I'm also a strong believer that TypeScript helps improving the code quality and maintainability. However, regarding 4. Use type inference for defining a component state or DefaultProps, I would say it might make it cleaner and readable, to define a single interface (or type) for the props, and after create the defaultProps object based on that interface. The way I do it is use a generic type, that defines a readonly type with all the properties as non-optional. These are the generic types that I use for that: gist.github.com/jbaez/71df88c47362...

I recently wrote an article using those generic types, it's about separating the logic of the component from the the UI (React), which also helps making the component/screen cleaner, specially on complex ones : dev.to/jbaez/decoupling-the-logic-...

Collapse
 
rbrtbrnschn profile image
Robert Bornschein

Great concept overall. But #5 is, simply put, is quite misleading.

A interface can be a type but a type cannot be an interface. A square is always a rectangle but a rectangle isn't always a square.

This article explains it well enough.
blog.logrocket.com/types-vs-interf...

Collapse
 
vijayiyer profile image
Vijay Iyer

I can't see the 'code below' in any of the points. Am I missing something?