jimzhou
jimzhou

Reputation: 119

useReducer confusion as to why is dispatch needed?

After studied both useState and useReducer, I am confused by useReducer's code, so reducer takes two argument (state, action), is the state same as the initialState, if so why use two different names? Second, useReduer takes two arguments (reducer, initialState), and return dispatch and state objects. So does it means actions from reducer happen first and then we put that inside useReducer hook, which is like a container for all kinds of actions?

I mean once some actions it performed, the state changed. This is like useState hook, so reducer function is similar to setState, so the reasons we use useReducers is probably becasue it returns dispatch function, that can basically do so many actions? I mean it comes down to have many useState hooks VS. one single useReducer?

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

Upvotes: 1

Views: 749

Answers (1)

monim
monim

Reputation: 4383

to answer your first question the state same as the initialState actually they're not :

const [state, setState] = useState(initialState);
const [state, dispatch] = useReducer(reducer, initialState );

An initial state is provided both for useState and useReducer is not the state it is just the initial value you're giving to the state. which will be updated later.

useReduer takes two arguments (reducer, initialState), and returns dispatch and the current state. in the dispatch function (triggered on an event like onClick ... ) Whatever argument given to it will be passed along to the reducer as its second argument and the first argument is the current state . finally useReduer will return the current state depending on that action.

FINALLY, you're right one of the reasons we use useReducers because it returns the dispatch function, which can basically do so many actions which give more control to manage the state. and they provide more advantages like testing because reducers do not depend on React. they are pure function with no side effects

Upvotes: 0

Related Questions