Jay
Jay

Reputation: 41

reduxjs toolkit (RTK) actions vs reducers in createSlice function

import { createSlice } from '@reduxjs/toolkit'

const initialState = { value: 0 }

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

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

In the second last line while exporting, why { increment, decrement, incrementByAmount } are destructured from "counterSlice.actions" instead of "counterSlice.reducers"?

// Please specify in comments if I missed something. ;) Thanks

Upvotes: 0

Views: 380

Answers (2)

phry
phry

Reputation: 44078

Because RTK makes one single reducer out of all the reducers you put in - and then automatically generates an action creator for every of those reducers.

You have to differentiate between "what you put in" and "what you get out" here - if you would get out what you put in you wouldn't need the whole thing in the first place ;)

Upvotes: 1

VMT
VMT

Reputation: 819

Because createSlice() will return object like below:

export interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string> {
    name: Name;
    reducer: Reducer<State>;
    actions: CaseReducerActions<CaseReducers>;
    caseReducers: SliceDefinedCaseReducers<CaseReducers>;
    getInitialState: () => State;
}

you can find it in createSlice.d.ts file, with path: node_modules\@reduxjs\toolkit\dist\createSlice.d.ts.

CaseReducerActions of action key is object contain action {increment, decrement, incrementByAmount}

Upvotes: 0

Related Questions