💻 Exemplos: Capítulo 15: Estado Global de Alta Escala com Redux Toolkit (RTK)
Especialização Frontend com React & TypeScript • Demonstrações Práticas Executáveis
🎯 Contexto e Objetivo Prático
Arquitetura corporativa com Redux Toolkit (RTK), slices fortemente tipados, reducers com Immer e custom hooks typed.
💻 Código Fonte React 19 (TSX)
// counterSlice.ts
import { createSlice, PayloadAction, configureStore } from "@reduxjs/toolkit";
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
export interface CounterState {
value: number;
history: number[];
}
const initialState: CounterState = {
value: 0,
history: [0]
};
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: state => {
state.value += 1;
state.history.push(state.value);
},
decrement: state => {
state.value -= 1;
state.history.push(state.value);
},
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload;
state.history.push(state.value);
}
}
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
// Configuração da Store Corporativa
export const store = configureStore({
reducer: {
counter: counterSlice.reducer
}
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
// Hooks Tipados
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
🖥️ Saída de Renderização Visual e Comportamento
[Redux Toolkit Store Inicializada]
Estado Inicial: { counter: { value: 0, history: [0] } }
Dispatch: incrementByAmount(10)
Novo Estado: { counter: { value: 10, history: [0, 10] } }