Using React with TypeScript

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


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

Class Components


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

Pure Components


  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


  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:


  onChange = (e: React.FormEvent<HTMLInputElement>): void => {
    // ?
  };
  

  const onChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    console.log(e);
  };
    
  

3. Hooks:


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

Could also pass boolean value if state is boolean.


  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.


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

extend it.


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

or type-check them.


  type NewButtonProps = ComponentProps<
    typeof NewButton
  >;
  

4. Context:

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


  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, 2023