React - The Complete Guide

Section 19: Diving Deeper into Redux - A Closer Look

olivia_yj 2023. 2. 10. 05:35

The goals

💪🏻Handling Async Tasks with Redux

✌🏻Where to Put Our Code

👍🏻The Redux DevTools

 

 

Sigining Provider in index.js so we can use it everywhere.

When we try to make toggle button, we can use 'useSelector'.

 

In store folder, we can organize the function we need separated by the types.

 

createSlice

A function that accepts an initial state, an object of reducer functions, and a "slice name", and automatically generates action creators and action types that correspond to the reducers and state.

This API is the standard approach for writing Redux logic.

Internally, it uses createAction and createReducer, so you may also use Immer to write "mutating" immutable updates:

 

import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

interface CounterState {
  value: number
}

const initialState = { value: 0 } as CounterState

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

export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer

Parameters

createSlice accepts a single configuration object parameter, with the following options:

function createSlice({
    // A name, used in action types
    name: string,
    // The initial state for the reducer
    initialState: any,
    // An object of "case reducers". Key names will be used to generate actions.
    reducers: Object<string, ReducerFunction | ReducerAndPrepareObject>
    // A "builder callback" function used to add more reducers, or
    // an additional object of "case reducers", where the keys should be other
    // action types
    extraReducers?:
    | Object<string, ReducerFunction>
    | ((builder: ActionReducerMapBuilder<State>) => void)

 

Never send any asynchronous code in reducer!

In react, being immutable is important! So try to keep the immunity of variables or states.


PUT vs POST

PUT is to replace the original value with the new value.