loading...

Discussion on: How To Use Redux in your React TypeScript App

Collapse
markerikson profile image
Mark Erikson

Hi, I'm a Redux maintainer. I would actually recommend changing most of the code in this article.

First, you should be using our official Redux Toolkit package, which is our recommended approach to writing Redux logic. It's already written in TS, and includes APIs like:

  • configureStore, which automatically adds the thunk middleware and sets up the Redux DevTools Extension for you
  • createSlice, which automatically generates action creators and action types, based on your reducers, and uses Immer internally to let you write "mutating" update logic that gets turned into safe correct immutable updates
  • createAsyncThunk, which automatically dispatches actions based on a promise

We already have an official Redux+TS template for Create-React-App, which comes with RTK already set up:

github.com/reduxjs/cra-template-re...

which you can install with create-react-app --template redux-typescript.

We also recommend inferring the type of the root state based on the return value of your root reducer:

redux-toolkit.js.org/usage/usage-w...

and would recommend against trying to specifically define the set of action types that can be dispatched. Instead, just make sure that the actions a reducer handles are correctly typed, which happens automatically if you're using createSlice.

As a side note, the community consensus is that you should avoid using React.FC:

fettblog.eu/typescript-react-why-i...

These approaches will drastically simplify the amount of actual code and the amount of types you have to write.