Darkpsinight
Darkpsinight

Reputation: 649

slice, action and reducers, what are they?

I'm trying to learn Redux, and i encountered this code:

reducers: {
    loginStart: (state) => {
      //...
    },
    loginSuccess: (state, action) => {
      //...
    },
    loginFailure: (state) => {
      //...
    },
    logout: (state) => {
      //...
    },
  },
});
export const { loginStart, loginSuccess, loginFailure, logout } = userSlice.actions;
export default userSlice.reducer;

I can't understand well what are .actions, Slice, .reducer or reducers from different web sources. So kindly can any expert in Redux here explain in a simplified way what are theses and their roles?

Upvotes: 3

Views: 8450

Answers (1)

Diyako
Diyako

Reputation: 661

Every state of your app (which is global) lives in an object tree stored in a single store.

Actions are simply JavaScript objects that have a type with a payload of data illustrating exactly what is happening. what they do? they are the only way to manage our state tree. pay attention: no state has been mutated so far.

Reducers are just responses to our corresponding called action to perform on our immutable state and thus returning a new state. optionally you might also want to check Array.reduce() method to better understand reducers.

What is slice then? as it comes with redux-toolkit, slice contains all the reducer logics and actions for a single feature. it auto generates your action creators and types which you have to define them as constants before redux-toolkit. check createSlice for the full explanation.

In your example the object called reducers goes into your createSlice with also an initial state and a name.

Based on all that being said, this is your final example of your question:

const initialState = {}
const authSlice = createSlice({
    name: 'authentication',
    initialState,
    reducers: {
        loginStart: (state) => {
          //...
        },
        loginSuccess: (state, action) => {
          //...
        },
        loginFailure: (state) => {
          //...
        },
        logout: (state) => {
          //...
        },
    },
})
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer

Upvotes: 2

Related Questions