Blog>
Snippets

Enhanced TypeScript Support in Redux Toolkit 2.0

Highlight how Redux Toolkit 2.0 improves TypeScript usage by providing better type inference, action types, and payload types without the need for manual types declaration.
// Define a simple Redux state and a reducer with createSlice
const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment(state) {
      return state + 1;
    },
    decrement(state) {
      return state - 1;
    },
    addBy(state, action: PayloadAction<number>) {
      return state + action.payload;
    },
  },
});

// Generate actions and reducer
const { actions, reducer } = counterSlice;
export const { increment, decrement, addBy } = actions;
export default reducer;
In this code, we define a Redux slice for a counter feature using Redux Toolkit's createSlice function. With Redux Toolkit 2.0, TypeScript types are inferred automatically, without the need to manually declare action types or payload types. The PayloadAction helper type is used to define the type of the action payload for 'addBy'. Note: This example assumes the installation of Redux Toolkit and its usage in a TypeScript environment.
// Use the useEffect hook with useDispatch and useSelector in a React component
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement, addBy } from './counterSlice';

export function CounterComponent() {
  const dispatch = useDispatch();
  const count = useSelector((state: RootState) => state.counter);

  useEffect(() => {
    dispatch(increment());
  }, [dispatch]);

  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
      <button onClick={() => dispatch(addBy(5))}>Add By 5</button>
    </div>
  );
}
This React component example utilizes Redux Toolkit hooks useDispatch and useSelector to interact with the Redux store. When the component mounts, it dispatches the 'increment' action, thanks to the useEffect hook. The component displays the counter state and provides buttons to increment, decrement, or add a specific number to the counter. The state type is inferred automatically when used with Redux Toolkit's typed hooks.
/* Style for CounterComponent */
.counter-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.counter-container button {
  margin: 5px;
}
Styles for the CounterComponent are written in CSS. Here we style the container to have a flex layout and center-align its child elements, which include the count display and action buttons. Each button is given a margin for better visual separation.