Home > Mobile >  Should we have a different action type for every time we update a react context state?
Should we have a different action type for every time we update a react context state?

Time:04-06

Say we have built everything in a large Context and we are using this context for state management (maybe better suited with redux... but regardless...)

Do we want to have a new action type for every time we want to update one property of the state? Or should we have a generic action like UPDATE_STATE in the reducer that handles the times we have a simple change that doesn't really have any reduction logic.

For example:

switch(action.type) {
  case "SET_MODAL":
    return {
      ...state,
      isModalOpen: action.isModalOpen
    }
  case "SET_ERROR_MSG":
    return {
      ...state,
      errMsg: action.errMsg
    }
  case "SET_HAS_CLICKED_THING":
    return {
      ...state,
      clickedThing: action.clickedThing
    }
   // ***ALOT MORE OF THESE^^^***
   // ***ALOT MORE OF THESE^^^***
  case "GET_ITEMS_SUCCESS":
    const { items } = action
    const newItems = items.map(*some reduction change logic that is not standard*)
    return {
      ...state,
      items: newItems
    }
}

vs

switch(action.type) {
  case "UPDATE_STATE":
    return {
      ...state,
      ...action.state
    }
  case "GET_ITEMS_SUCCESS":
    const { items } = action
    const newItems = items.map(*some reduction change logic that is not standard*)
    return {
      ...state,
      items: newItems
    }
}

It seems like we will have a large list of actions that Im not sure is adding value. Really we just want to store a value in the state. Do we really need an action for every time we just want to update the state?

CodePudding user response:

It's up to you. But I would choose the first way. It seems more readable and much better to see data flow. Defining actions helps you to debug easily and find out what happens in the app.

  • Related