November 2, 2024

Insider Tech

Latest news, hottest deals, trusted reviews

Redux Toolkit Logo

Redux Toolkit Logo

TypeScript and Redux Toolkit: Setting up a Strongly-typed Store

TypeScript is a popular superset of JavaScript that adds static type checking to the language. By adding types to our code, we can catch bugs before they happen, make our code more readable, and make it easier to refactor and maintain our codebase. In this article, we’ll explore how to set up a Redux store using the Redux Toolkit and TypeScript, including defining types for actions, state, and the store itself, and using interfaces and classes to create strongly-typed reducers.

First, let’s start by creating a new project and adding the necessary dependencies. We’ll need to install the Redux Toolkit, the TypeScript types for React and Redux, and the TypeScript compiler itself. We can do this by running the following command:

npm install --save-dev @reduxjs/toolkit @types/react @types/react-redux typescript

Next, we need to set up a tsconfig.json file to configure the TypeScript compiler. We can do this by running the following command:

tsc --init

This will create a tsconfig.json file in the root of our project. In this file, we can configure various options for the TypeScript compiler, such as the target version of JavaScript, the module system, and the JSX factory. For our purposes, we’ll need to make sure that we set the “jsx” option to “react” and the “esModuleInterop” option to true.

With our dependencies and configuration set up, we can now create our store. We’ll start by creating a new folder called “store” in our project and creating a new file called “store.ts” inside of it. In this file, we’ll define our state, actions, and reducers.

import { configureStore } from "@reduxjs/toolkit";

interface AppState {
  count: number;
}

const initialState: AppState = {
  count: 0
};

const store = configureStore({
  reducer: {
    count: (state = initialState) => {
      state.count++;
      return state;
    }
  }
});

export default store;

Here, we’ve defined an interface called “AppState” that describes the shape of our state. We’ve also defined an initial state object and a reducer that increments the count property of the state. We then use the configureStore function from the @reduxjs/toolkit to create our store and passed the initial state and the reducer

With our store set up, we can now use it in our components. To do this, we’ll need to install the react-redux library and its types:

npm install --save react-redux @types/react-redux

With the library installed, we can now use the useSelector hook to access the state and the useDispa`tch hook to dispatch actions.

import { useSelector, useDispatch } from "react-redux";

interface AppProps {
  count: number;
}

const App: React.FC<AppProps> = (props) => {
  const count = useSelector((state: AppState) => state.count);
  const