React Stateless Functional Component with TypeScript

React is one of the awesome JavaScript libraries. I’d like to write about Stateless Functional Component.

Conclusion

  • Use React Stateless Functional Component when you don’t need to manage states in a component.
  • TypeScript supports SFC type that is the alias of StatelessComponent interface.

In some cases, a functional component may occur performance issues. because we can not control rendering using shouldComponentUpdate() in SFC. Therefore, I should add the note “Depending on the position, you may use” to my conclusion. Thanks feedback Sebastian Kappen

Versions

  • React 15.4
  • TypeScript 2.2

What is Stateless Functional Component?

Stateless Functional Component (SFC) is just a regular React component. But by remembering it, we can keep the code simple & clear.

According to the official document, The simplest code to define a minimum stateless component is:

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

The above function can be replaced using Arrow Function in ECMA2015:

const Welcome = (props) => {
return <h1>Hello, {props.name}</h1>;
}

Combination of SFC and TypeScript

TypeScript is a typed superset of JavaScript.

It is a wise way to choose the suitable alternative JavaScript developed by Microsoft to bring peace to the world.

The above‐mentioned code using Arrow Function is clear. However, it does not benefit from type definitions of the big project.

So, add an interface definition to SFC:

import * as React from “react”
interface WelcomeProps {
name: string,
}
const Welcome: React.SFC<WelcomeProps> = (props) => {
return <h1>Hello, {props.name}</h1>;
}

The component defined an interface is more explicit than vanilla functional components. Users of WelcomeComponent can realize that name parameter is a required prop to use it.

If you want to set some default values to props, please use the static method.

import * as React from “react”
interface WelcomeProps {
name?: string, // Change the required prop to an optional prop.
}
const Welcome: React.SFC<WelcomeProps> = (props) => {
return <h1>Hello, {props.name}</h1>;
}
Welcome.defaultProps = {
name: “Guest User”, // This value is adopted when name prop is omitted.
}

SFC interface is defined in @types/react/index/d.ts:

type SFC<P> = StatelessComponent<P>;
interface StatelessComponent<P> {
(props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
propTypes?: ValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}

React with TypeScript is a robust solution for web application developers almost without exception.

By using SFC, You can build stateless components clearly without writing Class. Additionally, if you indicate types, JSX will become a friendly script for humans.