All Posts
Mar 30, 2025

Typescript with React Part 2

This section is focussed on typing React hooks

Featured image for Typescript with React Part 2

Introduction

  • This article is a continuation of Typescript with React.
  • In the previous article, we explored how to use TypeScript with various types of props in React.
  • In this installment, we will focus on different use cases of TypeScript with React Hooks.

Type Inference in TypeScript

TypeScript has a powerful feature called type inference, which means it can automatically determine the type of a variable based on its initial value. This helps reduce the need for explicitly defining types while still maintaining type safety.

Type Inference

Example of Type Inference

When you assign a value to a variable, TypeScript infers the type automatically:

let count = 10; // Inferred as number
count = "hello"; // ❌ Type error: Type 'string' is not assignable to type 'number'.

Here, TypeScript knows that count is a number because of the initial value 10, so it prevents assigning a string to it.

Similarly, TypeScript infers the type for function return values:

function getMessage() {
return "Hello, TypeScript!";
}
const message = getMessage(); // Inferred as string

However, when a variable is initialized as null or undefined, TypeScript doesn’t know its intended type:

let user = null; // Inferred as null
user = { name: "John" }; // ❌ Type error

To fix this you should explicitly define the type:

let user: { name: string } | null = null;
user = { name: "John" }; // ✅ Works fine

Defining Types in useState Hook

When using React's useState hook with TypeScript, TypeScript will infer the type from the initial state. However, in some cases, explicitly defining the type is necessary to avoid issues.

Typing useState

1. Default Type Inference in useState

const [count, setCount] = useState(0); // Inferred as number
setCount(5); // ✅ Valid
setCount("ten"); // ❌ TypeScript error

Since 0 is a number, TypeScript infers count as number, and setCount can only accept numbers.

2. Explicitly Defining Types

If the initial value is null or complex, you should define the type explicitly using angle brackets (<>).

State with Numbers (Explicit Type Definition)

const [count, setCount] = useState<number>(0); // Explicitly defining count as number

State with Strings

const [name, setName] = useState<string>("John");

State with Objects

type User = { name: string; age: number };
const [user, setUser] = useState<User>({ name: "Nim", age: 40 });
setUser({ name: "Dave", age: 20 }); // ✅ Valid
setUser({ name: "Dave" }); // ❌ Error: Property 'age' is missing

State with Arrays

const [numbers, setNumbers] = useState<number[]>([]); // Explicitly defining an array of numbers
setNumbers([1, 2, 3]); // ✅ Valid
setNumbers(["a", "b"]); // ❌ Type error

State with null as Initial Value

If the state can be null, define it explicitly:

const [user, setUser] = useState<{ name: string } | null>(null);

3. Lazy Initialization with useState()

Normally, when we initialize state in useState, React assigns the value immediately:

const [count, setCount] = useState(5); // Direct initialization

This is fine for simple values, but if the initial state requires heavy computation, it could slow down the component rendering. Example includes:

  • Performing complex calculations
  • Fetching data from an API or local storage
  • Processing large datasets

How Lazy initialization works with useState()

Instead of passing the value directly, we pass a function to useState. This function will only run once, when the component first renders, and its return value will be used as the initial state.

const [count, setCount] = useState<number>(() => {
console.log("Computing initial state...");
return 5; // Computed only once
});

Why Does the Expensive Function Run Only Once?

When you pass a function to useState, React does not call the function on every render. Instead, it:

  1. Runs the function only on the initial render.
  2. Stores the returned value as the state.
  3. Ignores the function on subsequent renders, unless the component unmounts and remounts.

Example

function Counter() {
const [count, setCount] = useState(() => {
console.log("Computing initial state...");
return 5; // This only runs once
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// First render: "Computing initial state..." is logged, and count is set to 5.
// Subsequent re-renders (e.g., after clicking the button): The function is not called again.

When Does the Function Run Again?

The expensive function will run again if:

  1. The component unmounts and remounts.

    If you conditionally render the component and it unmounts, then React will re-run the function when it mounts again.

{isVisible && <Counter />}

If isVisible changes from false → true, the component mounts again, and the function executes.

  1. You reset the state manually.
const [count, setCount] = useState(() => computeExpensiveValue());
const reset = () => setCount(() => computeExpensiveValue()); // Runs the function again

How Is Lazy Initialization Related to TypeScript Type Declaration?

When we use lazy initialization with useState, the function inside useState must return a value of the correct explicitly defined type.

In TypeScript, we can specify the type using angle brackets (<>) to ensure that useState knows what type of value it should store.

Example:

const [count, setCount] = useState<number>(() => {
console.log("Computing initial value...");
return 5; // Ensures `count` is of type `number`
});

Here, we explicitly tell TypeScript that count is a number by using useState. If we don't do this, TypeScript will infer the type based on the function’s return value.

Understanding useReducer Hook in React

When managing complex state logic in React, the useState hook may not always be the best choice. This is where the useReducer hook comes in.

The useReducer hook is an alternative to useState for managing state transitions in a more structured way. It is particularly useful when the next state depends on the previous state or when handling multiple state updates in a centralized way.

useReducer Hook use case

How useReducer Works?

The useReducer hook works based on the Reducer Pattern, which involves three key components:

  1. State – The data we want to manage.
  2. Action – The event or instruction that tells React how to update the state.
  3. Reducer Function – A pure function that takes the current state and an action and returns a new state.

useReducer hook structure

Basic Syntax of useReducer

const [state, dispatch] = useReducer(reducerFunction, initialState);
  • state – Holds the current state value.
  • dispatch – A function that we call to send ("dispatch") an action to update the state.
  • reducerFunction – A function that takes (state, action) and returns a new state.
  • initialState – The initial value of the state.

Example: Counter with useReducer

Let's build a simple counter app using useReducer to understand how it works.

Step 1: Create the Reducer Function

function counterReducer = (state, action) => {
if (action.type === 'increment') {
return state + 1;
}
if (action.type === 'decrement') {
return state - 1;
}
return state; // Default State: Return current state
}

Here:

  • state is a number (the counter value)
  • action is an object with a type property.
  • The reducer function checks the type and updates the state accordingly.

Step 2: Use useReducer in a Component

import { useReducer } from "react";
function Counter() {
const [count, dispatch] = useReducer(counterReducer, 0); // Initial state is 0
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</div>
);
}
export default Counter;

How it works?

  1. Initialize useReducer
const [count, dispatch] = useReducer(countReducer, 0);
  • count is the state (initially 0).
  • dispatch is a function that sends actions to update the state.
  • counterReducer is the reducer function that defines state updates.
  1. Trigger an Action with dispatch
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
  • When the button is clicked, the dispatch({ type: 'increment' }) sends an action.
  • The reducer function handles the action and updates the state.
  1. Reducer updates the State
  • The reducer function receives { type: "increment" }, increases the count, and returns the new state.
  • React rerenders the component with the updated state.

When to use useReducer instead of useState

  1. Use useState when the state logic is simple.
  2. Use useReducer when:
    • Multiple related state updates happen together.
    • The next state depends on the previous state.
    • The state logic is complex and needs better structure.
    • You want a more predictable state update pattern.

Defining Types in useReducer Hook

When using useReducer in TypeScript, it's important to define proper types for:

  • State – The shape of the state.
  • Actions – The allowed actions and their payloads.

Example: Managing Form state with useReducer

type State = {
name: string;
email: string;
}
type Action =
{ type: "SET_NAME"; payload: string; } |
{ type: "SET_EMAIL"; payload: string; }
const formReducer = (state: State, action: Action) => State {
switch(action) {
case "SET_NAME":
return { ...state, name: action.payload }
case "SET_EMAIL":
return { ...state, email: action.payload }
default:
return state
}
}
const Form = () => {
const [state, dispatch] = useReducer(formReducer, { name: "", email: "" })
return (
<div>
<input
type="text"
value={state.name}
onChange={(e) => dispatch({ type: "SET_NAME", payload: e.target.value })}
/>
<input
type="text"
value={state.name}
onChange={(e) => dispatch({ type: "SET_EMAIL", payload: e.target.value })}
/>
<p>Name: {state.name}</p>
<p>Email: {state.email}</p>
</div>
)
}

Conclusion

  • useReducer is great for managing complex state logic.
  • TypeScript helps by enforcing type safety for state and actions.
  • Defining types makes reducers predictable and easier to debug.

Understanding useContext Hook in React

The useContext hook is used to access values from a React Context. It helps avoid prop drilling by allowing components to consume values directly from a context provider.

It is commonly used when you have data that needs to be accessed by many components at different levels, such as the current theme, user authentication status, language settings, etc.

React Context

What is Context?

Context in React is a feature that allows you to share values (like data or functions) across different components, even if they're deeply nested, without passing them through props explicitly.

useContext Hook

The useContext hook lets you access the value of a context directly in your functional components.

Steps to Use useContext:

  1. Create a Context: First, we need to create a context using React.createContext(). This context will hold the value we want to share across components.
  2. Provide the Context Value: Using a Context.Provider component, we provide the value of the context to all components inside the provider.
  3. Consume the Context Value: Components that need the context value can use the useContext hook to access it.

Using React Context

Simple Example: Theme Switcher (Dark and Light Mode)

Let's create a simple theme switcher that uses useContext to toggle between light and dark modes.

1. Create a Context for the Theme

First, we create a context for the theme (light or dark).

import React, { createContext, useState } from 'react'
// Create a Context
const ThemeContext = createContext();
// Create a Provider Component
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light')
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'))
}
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
)
}

Here

  • ThemeContext is created using createContext.
  • ThemeProvider is a wrapper component that manages the theme state (light or dark) and provides the toggleTheme function.
  • The value provided to the ThemeContext.Provider is an object containing theme and toggleTheme.

2. Consume the Theme Context in Components

Now, let's consume the context in our main component where we display the theme and allow the user to toggle it.

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';
const ThemeSwitcher = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div style={{
backgroundColor: theme === 'light' ? '#fff' : '#333',
color: theme === 'light' ? '#000' : '#fff', minHeight: '100vh'
}}>
<h1>{theme === 'light' ? 'Light Mode' : 'Dark Mode'}</h1>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};

In this component:

  • We use useContext to access the theme and toggleTheme from the ThemeContext.
  • The background color and text color change based on the current theme.
  • The button allows users to toggle between light and dark modes by calling toggleTheme.

3. Wrap the App with ThemeProvider

Finally, we need to wrap the root of our app with the ThemeProvider so that the theme context is available to all components.

import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider } from './ThemeProvider';
import ThemeSwitcher from './ThemeSwitcher';
const App = () => (
<ThemeProvider>
<ThemeSwitcher />
</ThemeProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));

Summary:

  • useContext allows components to access shared data (like the theme) without having to pass props through every level.
  • A Provider component (like ThemeProvider) holds the state and provides it to the rest of the app.
  • useContext is used in functional components to read the context value, making it easier to manage global state in your app.