TypeScript with React

AresAres
4 min read

TypeScript is a statically typed superset of JavaScript that adds optional static typing, classes, and interfaces to the language. It's developed and maintained by Microsoft. React, on the other hand, is a JavaScript library for building user interfaces, created by Facebook. When combined, TypeScript and React offer a powerful toolset for building robust, scalable web applications. This article will delve into how to use TypeScript with React and the benefits it brings.

Why Use TypeScript with React?

There are several reasons why developers might choose to use TypeScript with React:

  1. Improved Type Checking: TypeScript offers variable checks by checking the data type assigned to statically-defined variables. This reduces the possibility of assigning the wrong types to variables.

  2. Enhanced Code Readability: With TypeScript, it's easy to define Prop types, making the code much easier to read and use.

  3. Better Tooling Support: TypeScript provides better IntelliSense and code completion for JSX.

  4. Safer Refactoring: TypeScript's static typing allows for safer refactoring as it can catch errors at compile time rather than runtime.

  5. Increased Scalability: For large codebases, TypeScript can make the code more manageable and easier to navigate.

How to Use TypeScript with React

Here are some steps on how to use TypeScript in your React projects:

  1. Installation: All production-grade React frameworks offer support for using TypeScript. You can create a new project with the --template typescript option or add TypeScript to an existing project.

  2. Understanding .tsx files: Every file containing JSX must use the .tsx file extension. This is a TypeScript-specific extension that tells TypeScript that this file contains JSX.

  3. Writing Components: Writing TypeScript with React is very similar to writing JavaScript with React. The key difference when working with a component is that you can provide types for your component’s props.

For example:

interface MyButtonProps {
  /** The text to display inside the button */
  title: string;
  /** Whether the button can be interacted with */
  disabled: boolean;
}

function MyButton({ title, disabled }: MyButtonProps) {
  return (
    <button disabled={disabled}>{title}</button>
  );
}

In this example, an interface is used to describe the component’s props.

Using Hooks with TypeScript

React Hooks are functions that let you hook into React state and lifecycle features from function components. They were introduced in React 16.8. Here's how you can use hooks in your TypeScript projects:

  1. useState: The useState hook lets you add state to function components. In TypeScript, you can explicitly declare the type of this state.
const [count, setCount] = useState<number>(0);

In this example, count is a state variable of type number, and setCount is a function used to update count.

  1. useEffect: The useEffect hook lets you perform side effects in function components. In TypeScript, you don't need to declare any types because this hook doesn't deal with returning values.
useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);

In this example, the document's title is updated every time count changes.

  1. useContext: The useContext hook lets you subscribe to React context without introducing nesting. In TypeScript, you need to declare the type of the context.
type MyContextType = {
  theme: string;
  toggleTheme: () => void;
};

const MyContext = createContext<MyContextType | undefined>(undefined);

const value = useContext(MyContext);

In this example, MyContext is a context object of type MyContextType, and value is the current context value for MyContext.

Using Context API with TypeScript

The Context API provides a way to pass data through the component tree without having to pass props down manually at every level. In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g., locale preference, UI theme) that are required by many components within an application. Here's how you can use Context API in your TypeScript projects:

  1. Creating Context: You create a Context object in your app using React.createContext. When creating a new context in TypeScript without default values, you need to define an interface that defines the values of your context.
interface IThemeContext {
  dark: boolean;
  toggleDark: () => void;
}

const ThemeContext = React.createContext<IThemeContext | undefined>(undefined);

In this example, ThemeContext is a context object of type IThemeContext.

  1. Providing Context: You can use a context provider to pass the current context value down the tree. All components below the provider will have access to the context value.
<ThemeContext.Provider value={{ dark: isDark, toggleDark }}>
  {children}
</ThemeContext.Provider>

In this example, ThemeContext.Provider is a context provider that passes down dark and toggleDark to all components below it.

  1. Consuming Context: You can use the useContext hook to consume the context.
const theme = useContext(ThemeContext);

In this example, theme is the current context value for ThemeContext.

Conclusion

In conclusion, using TypeScript with React offers numerous benefits including improved type checking, enhanced code readability, better tooling support, safer refactoring, and increased scalability. Whether you're a seasoned developer or just starting out, integrating TypeScript into your React projects can lead to more robust and maintainable codebases.

Remember, TypeScript is not a replacement for JavaScript but rather a tool that helps developers write safer and more understandable code. It's not necessary for every project, but it can be incredibly beneficial for larger projects or teams.

31
Subscribe to my newsletter

Read articles from Ares directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ares
Ares

Over-engineering my software