Blog>
Snippets

Type-Safe Store Configuration with Redux 5.0.0

Demonstrate how to set up a TypeScript-friendly Redux store using the enhanced createStore function with type safety for state and reducers.
import { configureStore } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import rootReducer from './reducers';

// Define a type for the store's state
export type AppState = ReturnType<typeof rootReducer>;

// Define a type for the dispatch function
export type AppDispatch = typeof store.dispatch;

// Create a store with a reducer, alongside any middleware/enhancements
const store = configureStore({
  reducer: rootReducer
});

// Export the store
export default store;

// Typed hooks that can be used in place of `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<AppState> = useSelector;
This code is setting up a Redux store using Redux Toolkit, which is designed to work well with TypeScript. The store's state type (`AppState`) and the dispatch function type (`AppDispatch`) are defined. A configured store is created with the `configureStore` method using the root reducer. Additionally, typed versions of `useDispatch` and `useSelector` hooks are exported for use within React components with type safety.