📊 Capítulo 07: useReducer & Máquinas de Estado
Especialização em Frontend com React
🗺️ O Fluxo Unidirecional de Ações do useReducer
flowchart LR
ACTION["dispatch({ type: 'ADICIONAR_ITEM', payload: novoItem })"]
--> REDUCER["function reducer(state, action): NovoEstado\n(Função pura / Sem efeitos colaterais)"]
REDUCER --> SWITCH{"switch (action.type)"}
SWITCH --> CASE1["'ADICIONAR_ITEM': return { ...state, itens: [...] }"]
SWITCH --> CASE2["'LIMPAR': return estadoInicial"]
SWITCH --> CASE_DEF["default: return state"]
REDUCER --> NEW_STATE["Novo Estado Imutável aplicado ao Componente!"]
style ACTION fill:#ede7f6,stroke:#512da8,stroke-width:2px
style REDUCER fill:#fff3e0,stroke:#ff9800,stroke-width:2px
style SWITCH fill:#e1f5fe,stroke:#03a9f4,stroke-width:1.5px
style CASE1 fill:#e8f5e9,stroke:#4caf50,stroke-width:1.5px
style CASE2 fill:#fff9c4,stroke:#fbc02d,stroke-width:1.5px
style CASE_DEF fill:#ffebee,stroke:#d32f2f,stroke-width:1.5px
style NEW_STATE fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px
🎯 Slide 1: useState vs useReducer
-
useState: Perfeito para valores primitivos independentes (contador,aberto,busca). useReducer: Ideal quando múltiplos valores de estado dependem uns dos outros ou quando as transições de estado seguem regras de negócio complexas.
🎯 Slide 2: Discriminated Unions nas Actions
type CarrinhoAction =
| { type: 'ADICIONAR'; item: Produto }
| { type: 'REMOVER'; id: string }
| { type: 'APLICAR_CUPOM'; codigo: string };
function carrinhoReducer(state: EstadoCarrinho, action: CarrinhoAction): EstadoCarrinho {
switch (action.type) {
case 'ADICIONAR': return { ...state, itens: [...state.itens, action.item] };
case 'REMOVER': return { ...state, itens: state.itens.filter(i => i.id !== action.id) };
case 'APLICAR_CUPOM': return { ...state, cupom: action.codigo };
}
}
🎯 Slide 3: Testabilidade Máxima
- Como a função
reduceré uma função pura isolada, ela pode ser testada em 100% com Vitest sem precisar renderizar nenhum componente ou DOM!
🔗 Navegação do Capítulo 07
| 📖 Ler Conteúdo Completo | 🧠 Fazer Quiz | 💻 Ver Exemplos | 🧩 Exercícios |
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim