Upgrading to Redux v5.0.0 with TypeScript
Outline the key considerations and modifications when upgrading a TypeScript+Redux codebase to Redux v5.0.0, ensuring type compliance.
import { configureStore } from '@reduxjs/toolkit';
const store = configureStore({
reducer: {
// your reducers here
},
// applyMiddleware and other store enhancers can be included here
});
export type AppState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
This code sets up the Redux store using configureStore from Redux Toolkit. AppState and AppDispatch types are exported for use throughout the application.
import { createAction, createReducer } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
interface CounterState {
value: number;
}
// Initial state
const initialState: CounterState = { value: 0 };
// Action Creator
export const increment = createAction('counter/increment');
// Reducer
export const counterReducer = createReducer(initialState, (builder) => {
builder.addCase(increment, (state, action: PayloadAction<void>) => {
state.value++;
});
// Other cases can be added here
});
This piece of code defines a reducer using createReducer from Redux Toolkit with proper TypeScript annotations. It includes a sample counter state and an increment action.
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { AppState, AppDispatch } from './store';
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<AppState> = useSelector;
This code abstracts the standard useDispatch and useSelector hooks to include typing information specific to the app's state and dispatch functions.
import { Provider } from 'react-redux';
import store from './store';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
This snippet shows how the Redux store is provided to a React application using the <Provider> component from 'react-redux'.