5 ways to use Typescript in React

5 ways to use Typescript in React

A definitive guide to using Typescript in ReactJS

ยท

3 min read

Use Strong Types Props in Functional Component

First we define a functional component with return type of FC which stands for Functional Component. This is Reacts built-in type. To import this use

import {FC} from "react"

Passing Props using Typescript helps you in evading lot of production level bugs. This helps catch bugs when we access data element which are not present in props.

For this first we need to define the type of our props. we do this using interfaces. Using interface is cool since it gives us useful intellisence when using props object.

Screenshot from 2021-07-07 19-27-33.png

Defining Interface for Props using Typescript

Here is the App.tsx file in Typescript. I have used IAppProps to define type of props in code. I in the IAppProps stands form interface.

import React, { FC } from 'react';


interface IAppProps {
  name: String;
  age?: Number;
}

const App: FC<IAppProps> = (props) => {
  return (
    <div>
      <h1>{props.name}</h1>
      <p>{props.age}</p>
    </div>
  );
};

export default App;

Use Strong Types States in Functional Component

Strong typing in state will help you evade bugs related to changed data types. Consider this you have set your state as const [state, setState] = useState({text : "Hello world"}) but in code you access your state via {state}.

Screenshot from 2021-07-07 21-53-39.png

By default the datatype of useState is string but we can explicitly define type of useState using interfaces which means you can define complex objects in useState.

This will give you the intellisence feature as a reward for defining your types.

Screenshot from 2021-07-07 21-55-47.png

import React, { FC, useState } from 'react';

interface IAppProps {
  name: String;
  age?: Number;
}

const App: FC<IAppProps> = (props) => {
  const [state, setState] = useState<string>('');
  return (
    <div>
      <button onClick={() => setState('๐Ÿฐ')}></button>
      <h1>{state}</h1>
      <p>A cake for you {props.name}</p>
    </div>
  );
};

export default App;

Use Strong Types Context in Functional Component

React context allows you to share data between several components in the same tree. Contexts are used to provide theming information, maintain global state, so that all components can access it. Typescript makes this easier because it knows the type for context.

TypeScript offers the powerful tool of inference. This is very useful for strongly-typed contexts.

We start by creating a theme using the createContext function of React.

const defaultTheme = "white";
const ThemeContext = React.createContext(defaultTheme);

Now we have theme

type Props = {
  children: React.ReactNode
};
export const ThemeProvider = ({ children }: Props) => {
    const [theme, setTheme] = React.useState(defaultTheme);

    React.useEffect(() => {
        const currentTheme = "lightblue";
        setTheme(currentTheme);
    }, []);

  return (
    <ThemeContext.Provider value={ theme }>
      {children}
    </ThemeContext.Provider>
  );
};

The type for a React context is correctly inferred if we provide a sensible default upon creation. You can extend this basic concept to more complex strongly-typed contexts.

Use Strong Types Event Handlers in Functional Component

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  setCriteria(e.currentTarget.value);
};

TypeScript has inferred the type, making the inline event handler strongly-typed hence we dont need types for them. Now, with that event handler, a user can enter criteria into input. If we want to create a named event handler function, we must hover over the event handler prop to learn what the function parameter type should be. This is the power of Typescript.

Use Strong Types Refs in Functional Component

Just like how we strongly typed our local state in functional components we also can strongly type our reference using similar syntax. By default the Type of useRef is undefined

const element = React.useRef<ElementType>(null);

Strong typing also applies for creating references, through the createRef hook.

const element = React.createRef<ElementType>();

Did you find this article valuable?

Support Sourabh Mandal by becoming a sponsor. Any amount is appreciated!