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

Lawrence Eagles
Lawrence Eagles
4
Feb
2022
|
7 min read
Clean code is a reader-focused development style that improves our software quality and maintainability. Here are the 10 most important patterns that'll help you write clean code with React and TypeScript.

React is a JavaScript library, and it is the most popular and industry-leading frontend development library today.

JavaScript is a loosely typed language, and as a result, it catches runtime. The result of this is that JavaScript errors are caught very late and this can lead to nasty bugs. As a JavaScript library, React inherits this problem.

Clean code is a consistent style of programming that makes your code easier to write, read, and maintain. Anyone can write code that a computer can understand but good developers write clean code – code that humans can understand.

Clean code is a reader-focused development style that improves our software quality and maintainability.

Writing clean code involves writing codes with clear and simple design patterns that makes it easy for humans to read, test and maintain. Consequently, clean code can lower the cost of software development. And this is because the principles involved in writing clean code, eliminates technical debts.

In this article, we would look at some useful patterns to use when working with React and TypeScript.

💡 To make it easier for your team to keep codebase healthy and prioritise technical debt work, try using Stepsize. Track and manage actionable issues that are linked to code, directly from the IDE.

Now let’s learn about the ten useful patterns to apply when using React and Typescript:

React and TypeScript Patterns

Below are ten useful patterns to apply when using React and Typescript:

1. Use Default import to import React

Consider the code below:

CODE: https://gist.github.com/mebinum/a336167b97d410ea6df25146fa501658.js

While the code above works, it is confusing and not a good practice to import all the contents of React if we are not using them. A better pattern is to use default export as seen below:

CODE: https://gist.github.com/lawrenceagles/c6de59538119ee33d9c2e71c64620a56.js

With this approach, we can destructure what we need from the react module instead of importing all the contents.

Note: To use this option, we need to configure the tsconfig.json file as seen below:

CODE: https://gist.github.com/lawrenceagles/d704140bbe003cd05be31b6ae7120468.js

In the code above, by setting esModuleInterop to true we enable allowSyntheticDefaultImports which is important for TypeScript to support our syntax.

2. Declare types before runtime implementation

Consider the code below:

CODE: https://gist.github.com/lawrenceagles/f7b5daad358c0e9f3623baa83474ab01.js

The code above can be cleaner and more readable if we separate the runtime and compile-time declarations. And this is done by declaring the types — the compile type declarations first. 

Consider the code below:

CODE: https://gist.github.com/lawrenceagles/317170a0b580b92738a94fce7197be17.js

Now at first glance, a developer knows what the component API looks like since the first line of the code clearly shows this. 

Also, we have separated our compile-time declarations from our runtime declarations.

3. Always provide explicit type of children Props

TypeScript mirrors how React handles children props by annotating it as optional in the react.d.ts for both functional and class components. Consequently, we are required to explicitly provide a type for the children props. However, it is best practice to always explicitly annotate children props with a type. This is useful in cases where we want to use children for content projection, and if our component does not use it, we can simply annotate it with the never type.

Consider the code below:

CODE: https://gist.github.com/lawrenceagles/45672ae71f63904fa7f6c88ec5a90e75.js

Below are some valid types to annotate the children props:

  • ReactNode | ReactChild | ReactElement
  • For primitive we can use string | number | boolean
  • Object and Arrays are also valid types
  • never | null | undefined – Note: null and undefined are not recommended

4. Use type inference for defining a component state or DefaultProps

CODE: https://gist.github.com/lawrenceagles/05c4c6b8ff5930776a0febab60ce53f8.js

While the code above works we can refactor it for the following improvements:

  • To enable TypeScript’s type system to correctly infer readonly types such as DefaultProps and initialState
  • To prevent developer bugs arising from accidentally setting state: this.state = {}

Consider the code below:

CODE: https://gist.github.com/lawrenceagles/6e4ea2442091e86b3903738d21f0b613.js

In the code above, by freezing the DefaultProps and initialState the TypeScript type system can now infer them as readonly types. 

Also, by marking both static defaultProps and state as readonly within the class we eliminate the possibility of runtime errors arising from setting state as mentioned above.

5. Use type alias instead of interface for declaring Props/State

While interface can be used, for consistency and clearness sake it is best to use type alias as there are cases where interface cannot work. For instance, in the previous example, we refactored our code to enable TypeScript’s type system to correctly infer readonly types by defining state type from implementation. We cannot use interface with this pattern as seen in the code below:

CODE: https://gist.github.com/lawrenceagles/74b89d92471cdadbba52065a87334549.js

Also, we cannot extend interface with types created by unions and intersection, so in these cases, we would have to use type alias.

6. Don’t use method declaration within interface/type alias

This ensures pattern consistency in our code as all members of type/inference are declared in the same way.

Also, --strictFunctionTypes works only when comparing functions and does not apply to methods. You can get further explanation from this TS issue.

CODE: https://gist.github.com/lawrenceagles/63cc5145646f5f02c4e28e36bd8af926.js

7. Don’t use FunctionComponent<P> or its shorthand FC<P> to define a function component

When using TypeScript with React, functional components can be written in two ways:

  1. As normal functions as seen in the code below:

CODE: https://gist.github.com/lawrenceagles/276112f9e5ed21c69ba02ffec755a7e1.js

  1. Using the React.FC or React.FunctionComponent as seen below:

CODE: https://gist.github.com/lawrenceagles/310dd40107547a3d3ed08ae782f767cf.js

Using FC provides some advantages such as type-checking and autocomplete for static properties like displayName, propTypes, and defaultProps. But it has a known issue of breaking defaultProps and other props: propTypes, contextTypes, displayName.

FC also provides an implicit type for children prop which also have known issues.

Also, as discussed earlier a component API should be explicit so an implicit type for children prop is not the best.

8. Don’t use constructor for class components

With the new class fields proposal, there is no need to use constructors in JavaScript classes anymore. Using constructors involves calling super() and passing props and this introduces unnecessary boilerplate plate and complexity.

We can write cleaner and more maintainable React class components by using class fields as seen below:

CODE: https://gist.github.com/lawrenceagles/ddd9bb947f736794db1d85d8b560f1f0.js

In the code above, we see that using class fields involves less boilerplate and we don’t have to deal with the this variable.

9. Don’t use public accessor within classes

CODE: https://gist.github.com/lawrenceagles/96e8c072ad43426b7306e77f1a462e4d.js

Since all members in a class are public by default and at runtime, there is no need to add extra boilerplate by explicitly using the public keyword.

Instead, use the pattern below:

CODE: https://gist.github.com/lawrenceagles/87da70d3cef765b652e9532b98b52921.js

10. Don’t use private accessor within Component class

CODE: https://gist.github.com/lawrenceagles/8e31307e752e5f6b93c901556bd1dfc1.js

In the code above, the private accessor only makes the fetchProfileByID method private on compile-time since it it is simply a TypeScript emulation. However, at runtime, the fetchProfileByID method is still public.

There are different ways to make the properties/methods private in a JavaScript class private one is to use the underscore (_) naming convention as seen below:

CODE: https://gist.github.com/lawrenceagles/d69d76d7c0c3c10c6e95af5354b0da2b.js

While this does not really make the fetchProfileByID method private it does a good job of communicating our intention to fellow developers that the specified method should be treated as a private method. Other techniques involve using weakmaps, symbols, and scoped variables.

But with the new ECMAScript class fields proposal we can do this easily and gracefully by using private fields as seen below:

CODE: https://gist.github.com/lawrenceagles/594c426e763afe26c12badf60432831e.js

And TypeScript supports the new JavaScript syntax for private fields from version 3.8 and above.

Bonus: Don’t use enum

Although enum is a reserved word in JavaScript, using enum is not a standard idiomatic JavaScript pattern.

But if you are coming from a language like C# or JAVA it might be very tempting to use enums. However, there are better patterns such as using compile type literals as seen below:

CODE: https://gist.github.com/lawrenceagles/2dd0ecbd8d54ceae715feedc81d445cb.js

Conclusion

Using TypeScript no doubt adds a lot of extra boilerplate to your code but the benefit is more than worth it.

To make your code cleaner and better don't forget to implement a robust TODO/issue process. It'll help your Engineering team get visibility on technical debt, collaborate on codebase issues and plan sprints better.

Never trawl through Slack, Jira or GitHub for updates again.

More articles

Date:
Duration:
minutes
No items found.
Clean code is a reader-focused development style that improves our software quality and maintainability. Here are the 10 most important patterns that'll help you write clean code with React and TypeScript.
No items found.