DEV Community

Sathish Kumar
Sathish Kumar

Posted on

React useReducer --- Basic Notes:

What it does: Takes the current state and an action, and returns a newState.

(state, action) => newState

Syntax:

const[score, dispatch] = useReducer ( reducerfn, initialvalue);

Main Parts:

1)​score (state): The current value/variable.

​ 2)dispatch: The function used to send an action.

​ 3)reducerFn: The function that decides how the state changes.

​ 4)initialValue: The starting value of the state.

​ 5)action: An object (like { type: "Increment" }) that tells what change to make.

Example:

const reducerFn = (state, action) => {
Enter fullscreen mode Exit fullscreen mode

switch (action.type) {

case "Increment":

  return state + 1;

case "Decrement":

  return state - 1;

case "Reset":

  return 0;

default:

  return state;
Enter fullscreen mode Exit fullscreen mode

}

};

Top comments (0)