Notes

Modern React Redux in 2020 with Hooks and Toolkit

Edit on GitHub

Redux
2 minutes

If you’re new to Redux, i highly suggest you start with using Redux Toolkit (@reduxjs/toolkit). This makes things simple and takes away a lot of boilerplate. If you then want to understand what is happening under the hood, or having difficulty understanding a particular Redux concept, only then go to the original Redux docs and figure out the details.

  • Hooks: useSelector() and useDispatch() (react-redux v7.1.0+. Previously you had to wrap your components in connect())
  • Redux Toolkit: createSlice(), createAction(), configureStore()

Redux Toolkit is just Redux with opinions and helper functions

No more mapStateToProps, mapStateToProps (both are Redux only, react-redux will give you connect() to handle both), action creators

useDispatch prevents us from using mapDispatch and connect

1useDispatch(fetchPokemonNames())
2
3const {pokemonTeam, favoritePokemon} = useState(state => state.pokemonTeam) // get the pokemonTeam array and favoritePokemon array from state

Redux Toolkit comes with Redux DevTools built-in and pre-configured

1// basic Store without any middleware
2import { configureStore } from '@reduxjs/toolkit'
3import rootReducer from './root-reducer'
4
5const store = () => configureStore({
6  reducer: rootReducer
7})
8
9export default store

Actions

With createAction() you no longer need action constants and action creators..

1const INCREMENT = 'counter/increment'
2
3function increment(amount) {
4  return {
5    type: INCREMENT,
6    payload: amount
7  }
8}
1const action = increment(3)
2// { type: 'counter/increment', payload: 3 }

would become this

1const increment = createAction('counter/increment')
1let action = increment()
2// { type: 'counter/increment' }
3action = increment(3)
4// returns { type: 'counter/increment', payload: 3 }