DEV Community


Posted on

How to Get the Root State type from your TypeScript React application.

One of the primary benefits of TypeScript is its static type checking, ensuring that the variables in your code are receiving the right things.

There are many instances in your application where you need to grab the type of the state, especially if you are using Redux and combining different state reducers into one root reducer.

Here is a quick guide to ensuring you always have the latest type of your state in your TypeScript React application!

Where Your Root State Lives in Redux

For those using redux, the state of the application doesn't live inside components necessarily, which is the case normally. Rather your components are connected to a 'store' of the global application state and get their information from that.

In most cases, you will have many 'reducers' that reduce certain state change actions, and these reducers will combine into a 'root reducer', that will combine all the states. It will look something like this:


import { combineReducers } from 'redux';

import userReducer from './..';
import shopReducer from './..';

const rootReducer = combineReducers({
    user: userReducer,
    shop: shopReducer
Enter fullscreen mode Exit fullscreen mode

Grabbing the State from the Root Reducer

If you remember, the rootReducer describes the state of your redux application. To grab the type, simply write the following export:

export type RootState = ReturnType<typeof rootReducer>;
Enter fullscreen mode Exit fullscreen mode
  • export type: so you can use the state type in other places
  • RootState: name of the type
  • ReturnType<>: returns the type of the return inside the <>
  • typeof rootReducer: the complicated redux type of the reducer that we will let TypeScript decode.

The benefit of this is that the type is not fixed; you can add or remove your reducers from the root reducer and your root state will update accordingly!

Thanks for reading :)

Top comments (2)

chazclark profile image
Chaz Clark

Thanks for the helpful tip. Just a note, if you're using redux-toolkit, the root state type is

export type RootState = ReturnType<typeof store.getState>

yusufzq profile image

Thanks for that Chaz! Haven't heard of redux-toolkit until now. It sounds useful