Notas de estudo sobre o workflow de implementação do React Redux Toolkit.

Related tags

counter-redux-workflow
Overview

Resumo: Redux Toolkit

Este projeto foi criado com Create React App, usando o Redux e Redux Toolkit como modelos.

Documentação: https://redux-toolkit.js.org

Quick Start: https://redux-toolkit.js.org/tutorials/quick-start

Exemplo com formulário: exercise-forms-redux

Observação

Esse método de implementação usa Hooks, ou seja, não funcionam em componentes de classe, apenas componentes funcionais.

Se tiver dúvidas sobre o funcionamento de Hooks em React consulte a documentação.

Instalação

Usando create react app

npx create-react-app my-app --template redux

Adicionando em um app

npm install @reduxjs/toolkit react-redux

API's

  • configureStore()
  • createReducer()
  • createAction()
  • createSlice()
  • createAsyncThunk
  • createEntityAdapter
  • createSelector

Implementado redux

Criando uma redux store

// src/app/store.js

import { configureStore } from '@reduxjs/toolkit'

export default configureStore({
  reducer: {},
})

Isso já configura o ReduxDevTools.

Provendo a redux store para o react

// index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import store from './app/store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Criando reducers e actions com createSlice()

Exemplo: Contador

// features/counter/counterSlice.js

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
  },
})

// As actions são criadas para da cada Reducer
export const { 
increment, 
decrement, 
incrementByAmount } = counterSlice.actions

// .reducer é a combinação dos três reducers
export default counterSlice.reducer

Importando slice/reducers para a store

// src/app/store.js

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
})

Usando states e actions redux nos componentes react

// features/counter/Counter.js

import React from 'react'
// Importamos os hooks para conectar o componente ao redux
import { useSelector, useDispatch } from 'react-redux'
// Importamos as actions para evoluirmos o estado na store
import { decrement, increment } from './counterSlice'

export function Counter() {
// useSelector() permite acessar o estado na store
  const { count } = useSelector((state) => state.counter)
  const dispatch = useDispatch()

  return (
    <div>
      <div>
        <button
          aria-label="Increment value"
          onClick={() => dispatch(increment())}
        >
          Increment
        </button>
        <span>{count}</span>
        <button
          aria-label="Decrement value"
          onClick={() => dispatch(decrement())}
        >
          Decrement
        </button>
      </div>
    </div>
  )
}

Explicando a estrutura de pastas e arquivos

A organização usa a lógica de "feature folders". Exemplo:

  • /src
    • index.jsx
    • /app
      • store.js
      • rootReducer.js (opcional)
      • App.js
      • /common (utiliátios e componentes genéricos)
    • /features
      • /counter
        • Counter.jsx (componente)
        • counterSlice.js (reducer, action)

A pasta 'pages' ainda pode ser usada no nível de preferência.

A pasta 'components', no exemplo, iria dentro de /counter e agruparia os componentes pertinente ao 'Counter.jsx'. Counter se comportaria como um sub app.

Owner
Thomas Ferreira
Web Development Student at Trybe | ADS Student at FATEC Taubaté | Profile picture: @candrawchris
Thomas Ferreira
The official, opinionated, batteries-included toolset for efficient Redux development

Redux Toolkit The official, opinionated, batteries-included toolset for efficient Redux development (Formerly known as "Redux Starter Kit") Installati

Redux 6.5k Oct 13, 2021
Redux-Toolkit example with React Hooks CRUD Application, Axios, Rest API, Bootstrap

Redux-Toolkit example with React Hooks CRUD Application, Axios, Rest API, Bootstrap

null 7 Oct 11, 2021
A Higher Order Component using react-redux to keep form state in a Redux store

redux-form You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of Redux

Redux Form 12.6k Oct 16, 2021
persist and rehydrate a redux store

Redux Persist Persist and rehydrate a redux store. v6 upgrade Web: no breaking changes React Native: Users must now explicitly pass their storage engi

Zack Story 11.6k Oct 12, 2021
A sample React TypeScript Redux Toolkit CRUD app

A sample React TypeScript Redux Toolkit CRUD app

Roger NDUTIYE 3 Oct 12, 2021
Thunk middleware for Redux

Redux Thunk Thunk middleware for Redux. npm install redux-thunk yarn add redux-thunk Note on 2.x Update Most tutorials today assume that you're using

Redux 16.7k Oct 19, 2021
:recycle: higher order reducer to add undo/redo functionality to redux state containers

redux undo/redo simple undo/redo functionality for redux state containers Protip: Check out the todos-with-undo example or the redux-undo-boilerplate

Daniel Bugl 2.7k Oct 15, 2021
Ruthlessly simple bindings to keep react-router and redux in sync

Project Deprecated This project is no longer maintained. For your Redux <-> Router syncing needs with React Router 4+, please see one of these librari

React Community 7.9k Oct 14, 2021
Thunk middleware for Redux

Redux Thunk Thunk middleware for Redux. npm install redux-thunk yarn add redux-thunk Note on 2.x Update Most tutorials today assume that you're using

Redux 16.7k Oct 13, 2021
RxJS middleware for action side effects in Redux using "Epics"

RxJS-based middleware for Redux. Compose and cancel async actions to create side effects and more. https://redux-observable.js.org Install This has pe

redux-observable 7.7k Oct 20, 2021
Official React bindings for Redux

React Redux Official React bindings for Redux. Performant and flexible. Installation Using Create React App The recommended way to start new apps with

Redux 21.5k Oct 15, 2021
Redux DevTools remotely.

Remote Redux DevTools Use Redux DevTools remotely for React Native, hybrid, desktop and server side Redux apps. Installation npm install --save-dev re

Mihail Diordiev 1.8k Oct 14, 2021
redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.

redux-immutable redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state. When Redux creat

Gajus Kuizinas 1.9k Oct 11, 2021
Redux bindings for client-side search

redux-search Higher-order Redux library for searching collections of objects. Search algorithms powered by js-worker-search. Check out the live demo a

Brian Vaughn 1.4k Oct 7, 2021
Selector library for Redux

Reselect Simple “selector” library for Redux (and others) inspired by getters in NuclearJS, subscriptions in re-frame and this proposal from speedskat

Redux 18.2k Oct 17, 2021
An i18n solution for React/Redux and React Native projects

redux-react-i18n An i18n solution with plural forms support for Redux/React Workers of all countries, unite! Supported languages list with expected co

Dmitry Erzunov 63 Sep 30, 2021
Logger for Redux

Logger for Redux Now maintained by LogRocket! LogRocket is a production Redux logging tool that lets you replay problems as if they happened in your o

null 5.6k Oct 13, 2021
DevTools for Redux with hot reloading, action replay, and customizable UI

Redux DevTools Developer Tools to power-up Redux development workflow or any other architecture which handles the state change (see integrations). It

Redux 12.1k Oct 12, 2021
DevTools for Redux with hot reloading, action replay, and customizable UI

Redux DevTools Developer Tools to power-up Redux development workflow or any other architecture which handles the state change (see integrations). It

Redux 12.1k Oct 14, 2021