Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 19

TypeScript with `useState`: Simple to Complex Data

Recommended resources

Hello! In our last lesson, we got our hands dirty with the useState hook, learning how to add, update, and manage state in your components. We touched on the importance of immutability and the functional update form.

Introduction

Today, we're going to layer on a crucial skill for building robust, enterprise-grade React applications: applying TypeScript to the useState hook. As a full-stack engineer proficient in TypeScript, you're already aware of the benefits of static typing—catching errors early, improving code clarity, and enabling powerful editor features like autocomplete. This lesson will show you how to bring that power directly into your component's state management.

Our goal is to apply TypeScript to the useState hook for managing both simple and complex data types. We'll cover when TypeScript's inference is sufficient, when you need to be explicit, and how to type common patterns like objects, arrays, and potentially null values.


Type Inference: When TypeScript Does the Work for You

For simple primitive values, TypeScript is smart enough to infer the type from the initial value you provide to useState.

// TypeScript infers the type as 'number'
const [count, setCount] = useState(0); 

// TypeScript infers the type as 'string'
const [text, setText] = useState('hello');

// TypeScript infers the type as 'boolean'
const [isActive, setIsActive] = useState(false);

In these cases, if you try to update the state with a value of a different type, the TypeScript compiler will immediately flag it as an error, preventing a potential runtime bug.

// This will cause a TypeScript error:
// Argument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'.
setCount('five'); 

This is the simplest scenario, and for basic state, you don't need to do any extra work.


Explicit Typing: When You Need to Guide TypeScript

There are common scenarios where TypeScript's inference isn't enough. This usually happens when the initial state doesn't fully represent all possible future states. In these cases, we use a generic type argument (the <Type> syntax) to explicitly tell useState what kind of data to expect.

Let's look at the most common situations.

1. The Initial Value is null or undefined

Imagine you're fetching user data. Before the data arrives, you might want the state to be null.

// If we do this, TypeScript infers the type as 'null'.
const [user, setUser] = useState(null);

// This will then fail, because you can't assign a User object to a state of type 'null'.
// setUser({ id: 1, name: 'John Doe' }); // Error!

The solution is to use a union type to tell TypeScript that the state can be either a User object or null.

interface User {
  id: number;
  name: string;
}

// Correct: State can be a User object or null.
const [user, setUser] = useState<User | null>(null);

// Now this is perfectly valid!
setUser({ id: 1, name: 'John Doe' });

2. The Initial Value is an Empty Array

A similar issue occurs with empty arrays. If you initialize state with [], TypeScript doesn't know what type of items the array will eventually hold. It infers the type as never[], meaning an array that can never have anything in it.

// Infers 'items' as type 'never[]'
const [items, setItems] = useState([]);

// This will fail because 'string' is not assignable to 'never'.
// setItems(['a', 'b', 'c']); // Error!

To fix this, you explicitly define the type of the array's elements.

// Correct: State is an array of strings.
const [items, setItems] = useState<string[]>([]);

// Correct: State is an array of Todo objects.
const [todos, setTodos] = useState<Todo[]>([]);

Mastering React Hooks with Typescript

The video 'Mastering React Hooks with Typescript' by Jack Herrington provides excellent, concise demonstrations of these two exact scenarios.

Please watch from 03:40 to 08:55. The first part (until 06:45) explains the empty array (never[]) problem and its solution. The second part (until 08:55) covers the null initial state pattern.

A Deeper Look: The useState Generic

The <...> syntax we're using is a TypeScript generic. Think of it as passing a type as a parameter to the useState function. Given your CS background, you might find it interesting to see how useState is actually typed within the React library itself.

Bonus: a generic type example from open source: useState itself!

The article 'React & TypeScript: use generics to improve your types' on devtrium.com has a fantastic section that dissects the type definition of useState.

Read the section titled 'Bonus: a generic type example from open source: useState itself!'. This will walk you through the useState<S> definition, explaining what S, Dispatch, and SetStateAction mean. It provides a solid theoretical foundation for the syntax we are using.

Understanding this shows that useState<User | null>(null) is not magic; you are simply providing the User | null type to the generic type variable S in React's own function definition.


Typing Complex Object State

The most common use case for explicit typing is managing object state. While TypeScript can infer the type of an object if you provide all properties initially, it's best practice to define an interface or type for your state object. This serves as a single source of truth and makes your code self-documenting.

Here's the pattern:

  1. Define an interface or type for the state object.
  2. Use that type as the generic argument for useState.
  3. Initialize the state with an object that conforms to your type.

This approach provides two major benefits:

  • Safety: TypeScript will ensure you can only set properties that exist on your type, preventing typos.
  • Autocomplete: Your editor will know the shape of your state object, providing helpful suggestions.

React useState With TypeScript (Typed useState TypeScript Tutorial)

The video 'React useState With TypeScript' by Cooper Codes provides a complete, practical walkthrough of this entire process, from setting up a component to handling typed events.

Please watch from 01:15 to 10:38. This comprehensive segment covers: Defining a custom interface for user input (01:15). Setting up a form and initializing useState with the custom type (02:02). Typing the onChange event and immutably updating the object state (05:16). Demonstrating the benefits of autocomplete and error prevention (09:16).

As the video demonstrates, when you update the object, you combine the TypeScript safety with the immutability rule from our last lesson, using the spread syntax to create a new object.

interface Profile {
  username: string;
  theme: 'light' | 'dark';
}

const [profile, setProfile] = useState<Profile>({ username: 'Guest', theme: 'light' });

function changeUsername(newUsername: string) {
  setProfile(currentProfile => ({
    ...currentProfile,
    username: newUsername
  }));
}

// TypeScript would throw an error on the line below because 'them' is a typo.
// setProfile(p => ({ ...p, them: 'dark' }));

Advanced Pattern: Discriminated Unions for State Machines

A powerful TypeScript pattern you can use with useState is a discriminated union. This is perfect for managing a set of related states, like the status of a data request (idle, loading, success, error).

Instead of managing separate boolean flags (isLoading, isError), you can represent the entire state machine in a single, type-safe object.

Understanding useState in TypeScript React

Let's look at a concise article from CodeParrot that explains this pattern clearly.

Please read the section 'Common patterns and best practices', focusing specifically on the sub-section about Discriminated Unions. It provides a clear RequestState type example that demonstrates this powerful pattern.

Here is the pattern from the article:

type RequestState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: string };

function MyComponent() {
  const [state, setState] = useState<RequestState<User[]>>({ status: 'idle' });

  // ... later in your component ...

  if (state.status === 'success') {
    // TypeScript knows that state.data exists here and is of type User[]
    return <ul>{state.data.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
  }

  if (state.status === 'error') {
    // TypeScript knows that state.error exists here and is a string
    return <p>{state.error}</p>;
  }

  // ... etc.
}

This pattern makes illegal states unrepresentable. For example, you can't accidentally have isLoading and isError be true at the same time. When you check the status property, TypeScript intelligently narrows the type, giving you access only to the properties valid for that specific state.

Test your understanding!

You are building an e-commerce feature. You need to manage the state for a single product that is fetched from an API.

The state should account for these requirements:

  1. The product data might not be loaded yet, so the initial state should be null.
  2. The product object has the following structure:
    • id: string
    • name: string
    • price: number
    • tags: an array of strings (can be empty)

Your task:

  1. Define a TypeScript interface named Product.
  2. Write the useState declaration for this product state, ensuring it is correctly typed to handle the null initial state.
  3. Write a function addTag(newTag: string) that takes a new tag and adds it to the product's tags array immutably. The function should do nothing if the product state is currently null.
Show answer
import { useState } from 'react';

// 1. Define the interface
interface Product {
  id: string;
  name: string;
  price: number;
  tags: string[];
}

function ProductPage() {
  // 2. Write the useState declaration
  const [product, setProduct] = useState<Product | null>(null);

  // 3. Write the update function
  function addTag(newTag: string) {
    // Use a type guard to ensure product is not null
    if (product) {
      setProduct(currentProduct => ({
        ...currentProduct,
        tags: [...currentProduct.tags, newTag] // Create new tags array
      }));
    }
  }

  // Example usage (not required by the problem)
  // Assume some effect calls setProduct with API data
  return (
    <div>
      <h1>{product?.name ?? 'Loading...'}</h1>
      <button onClick={() => addTag('new-arrival')}>Add Tag</button>
    </div>
  );
}

This solution correctly defines the Product interface, uses the Product | null union type for the state, and implements the addTag function with an immutable update, first checking if product exists.


Conclusion

You've now equipped your useState skills with the power and safety of TypeScript. This combination is fundamental to modern React development and will dramatically reduce bugs while improving your developer experience.

Key Takeaways:

  • Infer when possible: For simple, non-null initial values (numbers, strings, booleans), let TypeScript infer the type.
  • Be explicit when necessary: Use the generic syntax useState<Type>(...) in key scenarios:
    • When the initial value is null or undefined (e.g., useState<User | null>(null)).
    • When the initial value is an empty array (e.g., useState<string[]>([])).
    • When working with complex objects, to enforce a contract.
  • Define your types: Use interface or type to create a single source of truth for your state's shape.
  • Combine with immutability: Always create new objects and arrays when updating state, using patterns like the spread syntax (...).

Next Steps

In our next lesson, we will shift our focus from the "what" and "how" of state updates to the "when." We will explore the batching of state updates and its performance implications. You'll learn how React groups multiple setState calls into a single re-render to optimize performance, a concept we briefly encountered but will now examine in depth.