React and Typescript Cheatsheet

A cheatsheet to write React with TypeScript

This tutorial assumes you have the setup done with the usuals, such as ts-node and @types/react. If not, check out Setting up React with TypeScript before we continue.

Before we get started, we need to settle the usual debate between types and interface. The general rule of thumb is use type for states and props and interface for everything else.

Off we go.

1. Components:

Function Components

</>javascript
const Title = ({ title }: AppProps) => <h1>{title}</h1>

Class Components

</>javascript
class SubTitle extends Component<AppProps> {
    render() {
      return (
        <div>{this.props.subtitle}</div>
      );
    }
  }

Pure Components

</>javascript
class SubTitle extends PureComponent<SubTitleProps> {

Pure components doesn't re-render if parent component changes, it shallow compares state and props of its own component.

With state and props

</>javascript
interface SubTitle2Props = {
    message: string;
  };
  interface Subtitle2State = {
    name: string;
  };
  class SubTitle2 extends React.Component<SubTitle2Props, Subtitle2State> {
    state: MyState = {
      name: 'Guest'
    };
    render() {
      return (
        <div>{this.props.subtitle} {this.state.name}</div>
      );
    }
  }

Must pass arguments to the functions.

2. Events:

</>javascript
onChange = (e: React.FormEvent<HTMLInputElement>): void => {
    // ?
  };
</>javascript
const onChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    console.log(e);
  };

3. Hooks:

</>javascript
const [id, setId] = useState<Id | null>(null);

Could also pass boolean value if state is boolean.

</>javascript
const formRef = createRef<HTMLDivElement>();
  const formRef = useRef<HTMLDivElement>(null);

create-ref always returns a new ref while use-ref is persistent across multiple renders in a functional component.

4. Props:

With componentProps we can extract the props of an element. This is useful when working with third-party library which doesn't expose you their props.

Extract it.

</>javascript
import { ComponentProps } from "react";
  type ButtonProps = ComponentProps<"button">;

extend it.

</>javascript
type NewButtonProps = ComponentProps<"ButtonProps"> & {
    width: string;
  };

or type-check them.

</>javascript
type NewButtonProps = ComponentProps<
    typeof NewButton
  >;

4. Context:

Context allows you to pass props to another component without having to pass through components.

</>javascript
type Theme = "dark" | "light" | "system";
  const ThemeContext = createContext<Theme>("system");
  const theme = () => useContext(ThemeContext);
  //
  <p>The current theme is {theme}.</p>;
Posted on Jan 2, 2022