React - Redux Toolkit with TypeScript

React - Redux Toolkit with TypeScript

Introduction

As a developer, you’ve probably heard about Redux and its powerful state management capabilities. However, setting up Redux in a TypeScript-enabled React project can be a bit daunting. Fear not! In this article, we’ll walk through the process of installing Redux Toolkit (a fantastic abstraction over Redux) and integrating it with TypeScript. We’ll also create a simple counter app to demonstrate how it all comes together.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. Basic knowledge of React Hooks.
  2. Familiarity with Redux terms and concepts.
  3. Understanding of TypeScript syntax and concepts.

Step 1: Install Redux Toolkit and React-Redux

Let’s start by installing the necessary packages:

npm install @reduxjs/toolkit react-redux
        

Step 2: Create a Redux Store

In your project, set up a Redux store using configureStore. Here’s an example from your app/store.ts file:

import { configureStore } from '@reduxjs/toolkit';
import postsReducer from './features/posts/postsSlice';
import commentsReducer from './features/comments/commentsSlice';
import usersReducer from './features/users/usersSlice';

export const store = configureStore({
  reducer: {
    posts: postsReducer,
    comments: commentsReducer,
    users: usersReducer,
  },
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
        

Step 3: Define Typed Hooks

While you can import RootState and AppDispatch directly into your components, it’s better to create typed versions of the useDispatch and useSelector hooks. This ensures type safety and avoids repetitive typings:

// Create typed hooks
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './app/store';

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
        

Step 4: Create a Redux State Slice

Now let’s create a simple state slice for our counter app. In a new file (e.g., features/counter/counterSlice.ts), define your slice:

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0,
};

const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
  },
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
        

Step 5: Use Redux State and Actions in React Components

Finally, let’s use our counter slice in a React component:

// Counter.tsx
import React from 'react';
import { useAppSelector, useAppDispatch } from '../app/hooks';
import { increment, decrement } from '../features/counter/counterSlice';

const Counter: React.FC = () => {
  const count = useAppSelector((state) => state.counter.value);
  const dispatch = useAppDispatch();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
};

export default Counter;
        

Conclusion

You’ve successfully set up Redux Toolkit with TypeScript and created a basic counter app! Feel free to explore more features of Redux Toolkit and adapt them to your projects. Happy coding! ??


References:

  1. Redux Toolkit TypeScript Quick Start
  2. Redux Official Documentation - TypeScript Quick Start
  3. Medium Article: Quick Start with TypeScript, Linting, Redux & Router

要查看或添加评论,请登录

Hassan Fathy的更多文章

  • TypeScript - Types vs. Interfaces

    TypeScript - Types vs. Interfaces

    As TypeScript continues to gain popularity among developers for adding type safety to JavaScript, one of the frequent…

  • React - CSS Modules

    React - CSS Modules

    Introduction: In the bustling world of React development, there's a constant quest for more maintainable and scalable…

  • Typescript - Truthiness

    Typescript - Truthiness

    What is truthiness? Truthiness is a term coined by comedian Stephen Colbert to describe something that feels true, even…

  • React - React Router v6

    React - React Router v6

    React Router is a popular library for declarative routing in React web applications. It allows you to define routes as…

  • TypeScript - Equality

    TypeScript - Equality

    TypeScript’s static type checking adds a layer of complexity and safety to equality comparisons, but the JavaScript…

  • React - Hooks(useRef)

    React - Hooks(useRef)

    React's useRef is a hook, a special function that taps into React features in functional components. It returns a…

    2 条评论
  • TypeScript - typeof vs instanceof

    TypeScript - typeof vs instanceof

    Introduction: Unwrap the mysteries of type assertions in TypeScript with two powerful operators: typeof and instanceof.…

  • React - Hooks(useReducer)

    React - Hooks(useReducer)

    Introduction: In the evolving landscape of React, managing state efficiently is critical for crafting responsive and…

  • TypeScript - Type Guards / Narrowing

    TypeScript - Type Guards / Narrowing

    Introduction: In the dynamic world of web development, TypeScript has emerged as an essential tool for building robust…

  • React - Hooks (useMemo)

    React - Hooks (useMemo)

    ReactJS hooks are a powerful way to add state and effects to functional components. However, sometimes we need to…

社区洞察

其他会员也浏览了