Reference useReducer

  • useReducer is way of handling complex state and connecting the state to an action.
  • Example: 2 actions effect the state bit of state.
  • useReducer takes in a function and object of initial state.
  • useReducer detsructures 'state' and 'dispatch', which is the function.

0

WDS Video on this Hook
import React, { useReducer } from "react"; const ACTION = { INCREASE: "increase", DECREASE: "decrease", }; function reducer(state, action) { switch (action.type) { case ACTION.INCREASE: return { count: state.count + 1 }; case ACTION.DECREASE: return { count: state.count - 1 }; default: return state; } } function ExampleUseReducer() { const [state, dispatch] = useReducer(reducer, { count: 0 }); function increaseCount() { dispatch({ type: ACTION.INCREASE }); } function decreaseCount() { dispatch({ type: ACTION.DECREASE }); } return ( <Stack alignItems={"center"} sx={{ width: "100%", maxWidth: "40dvw", margin: 2, backgroundColor: "lightblue", padding: 7, borderRadius: 15 }}> <Stack direction={"row"} alignItems={"center"} gap={5}> <Button variant="contained" onClick={decreaseCount} disabled={state.count <= 0}> - </Button> <Typography>{state.count}</Typography> <Button variant="contained" onClick={increaseCount}> + </Button> </Stack> </Stack> ) }