1

I'm new to react, redux and tyring to understand the redux-toolkit tutorial i follow. I have the slice as follows.

const initialState = {
  count: 0,
};

export const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.count += 1;
    },
  },
});

export const { increment } = counterSlice.actions;

export default counterSlice.reducer;

export const incrementTest = () => (dispatch) => {
  dispatch(increment());
};

Then I use that incrementTest action as follows

<button onClick={() => dispatch(incrementTest())}> + </button>

I want to understand following.

In following fuction

export const incrementTest = () => (dispatch) => {
      dispatch(increment());
    };

we return a function which takes argument as dispatch then call that provided dispatch function with argement of another function increment which is defined above and exported.

However when we call this function we use dispatch(incrementTest()) providing incrementTest as a param to dispatch. I don't understand this concept . Which concept in javascript should i further study to learn this ?

Also increment reducer take state as parameter ( and action also in some cases ). Who provide this (state,action) to this function as we call it as dispatch(incrementTest())

1 Answer 1

2

So this:

export const incrementTest = () => (dispatch) => {
  dispatch(increment());
};

is an example for a thunk, a function that gets called (by a redux middleware) with two arguments, dispatch and getState. It is typically used to coordinate async work since you can await stuff inside the function or deal with promises. Look up the thunk middleware if you want to know more. I'm not sure why they made this action a thunk, there's no need for it, maybe testing.

To your second question, the library does. All you do is call dispatch() with an action, the library calls the reducer function with the current state and your action. Think of it as emitting an event. Your job is to create the event, the library takes care of updating the global state accordingly. The reducer is written declaratively, sort of. As in "how would the global state need to change if that specific event happened?".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.