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

Last update: Mar 30, 2022

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.

GitHub

https://github.com/WeltonThomasFerreira/counter-redux-workflow
You might also like...

A chart monitor for Redux DevTools https://www.npmjs.com/package/redux-devtools-chart-monitor

A chart monitor for Redux DevTools https://www.npmjs.com/package/redux-devtools-chart-monitor

Redux DevTools Chart Monitor This package was merged into redux-devtools monorepo. Please refer to that repository for the latest updates, issues and

May 3, 2022

An i18n solution for React/Redux and React Native projects

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

Sep 30, 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

Jul 31, 2022

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

Aug 8, 2022

A Soundcloud client built with React / Redux

SoundRedux NOTE It seems that SoundCloud has revoked my api client keys without any explanation or warning. Running the app locally no longer works un

Aug 7, 2022

Front-end of the movie application created with React.js and Redux

Front-end of the movie application created with React.js and Redux

# Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run:

Aug 21, 2021

Recipe Catalogue is a React & Redux web app based on a catalog of recipes.

Recipe Catalogue is a React & Redux web app based on a catalog of recipes.

Recipe Catalogue is a React & Redux web app based on a catalog of recipes. It contains a browsable list of meals that you can filter by category or type and access to one meal recipe. The data is retrieved from [Meals DB (https://www.themealdb.com/api.php) and then stored in the Redux store.

Mar 5, 2022

The ultimate React SSR, Redux-powered example.

The ultimate React SSR, Redux-powered example.

Redux server-side The ultimate React SSR, Redux-powered example. But why? Does any of the following sentences describe your SSR adventures? You'd love

Aug 20, 2021

This command line helps you create components, pages and even redux implementation for your react project

This command line helps you create components, pages and even redux implementation for your react project

react-help-create This command line helps you create components, pages and even redux implementation for your react project. How to install it? To ins

Apr 6, 2022
Redux Tutorial - share my experience regarding redux, react-redux and redux-toolkit
Redux Tutorial - share my experience regarding redux, react-redux and redux-toolkit

Redux Tutorial 1. Introduction to Redux 1.1 What is Redux & why Redux? A small JS Library for managing medium/large amount of states globally in your

Jul 28, 2022
A sample React TypeScript Redux Toolkit CRUD app
A sample React TypeScript Redux Toolkit CRUD app

A sample React TypeScript Redux Toolkit CRUD app

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

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

Aug 5, 2022
Toolkit for implementing clean architecture using Redux
Toolkit for implementing clean architecture using Redux

?? Toolkit for implementing clean architecture using Redux ?? ?? Focuses on achi

Jul 6, 2022
Skeleton React App configured with Redux store along with redux-thunk, redux persist and form validation using formik and yup

Getting Started with React-Redux App Some Configrations Needed You guys need to modify the baseUrl (path to your server) in the server.js file that is

Jul 10, 2022
A lightweight state management library for react inspired by redux and react-redux

A lightweight state management library for react inspired by redux and react-redux

Apr 1, 2022
A Higher Order Component using react-redux to keep form state in a Redux store
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

Aug 2, 2022
A simple app for study react with redux, redux saga and typescript.

React com Redux, Redux-Saga e TypeScript. ?? Uma aplicação simple para entender o funcionamento do Redux e a melhor maneira de utiliza-lo junto com o

May 24, 2022
Redux - Create forms using Redux And React
Redux - Create forms using Redux And React

Exercício de fixação Vamos criar formulários utilizando Redux! \o/ Antes de inic

Jul 21, 2022
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

Aug 5, 2022