#
Redux Toolkit TypeScript Quick StartWhat You'll Learn
- How to set up and use Redux Toolkit and React-Redux with TypeScript
Prerequisites
- Knowledge of React Hooks
- Understanding of Redux terms and concepts
- Understanding of TypeScript syntax and concepts
#
IntroductionWelcome to the Redux Toolkit TypeScript Quick Start tutorial! This tutorial will briefly show how to use TypeScript with Redux Toolkit.
This page focuses on just how to set up the TypeScript aspects . For explanations of what Redux is, how it works, and full examples of how to use Redux Toolkit, see the tutorials linked in the "Tutorials Overview" page.
The Redux+TS template for Create-React-App comes with a working example of these patterns already configured.
#
Project Setup#
Define Root State and Dispatch TypesUsing configureStore should not need any additional typings. You will, however, want to extract the RootState
type and the Dispatch
type so that they can be referenced as needed. Inferring these types from the store itself means that they correctly update as you add more state slices or modify middleware settings.
Since those are types, it's safe to export them directly from your store setup file such as app/store.ts
and import them directly into other files.
#
Define Typed HooksWhile it's possible to import the RootState
and AppDispatch
types into each component, it's better to create typed versions of the useDispatch
and useSelector
hooks for usage in your application. Since these are actual variables, not types, it's important to define them in a separate file such as app/hooks.ts
, not the store setup file. This allows you to import them into any component file that needs to use the hooks, and avoids potential circular import dependency issues.
#
Application Usage#
Define Slice State and Action TypesEach slice file should define a type for its initial state value, so that createSlice
can correctly infer the type of state
in each case reducer.
All generated actions should be defined using the PayloadAction<T>
type from Redux Toolkit, which takes the type of the action.payload
field as its generic argument.
You can safely import the RootState
type from the store file here. It's a circular import, but the TypeScript compiler can correctly handle that for types. This may be needed for use cases like writing selector functions.
#
Use Typed Hooks in ComponentsIn component files, import the pre-typed hooks instead of the standard hooks from React-Redux.
#
What's Next?See the "Usage with TypeScript" page for extended details on how to use Redux Toolkit's APIs with TypeScript.