DEV Community

Discussion on: Refactoring useState() To useReducer()

Collapse
 
daksamit profile image
Dominik Aksamit • Edited

During reading this article, I came up with an idea of what it might look like using a new vue 3 composition API.
And here we go:

<template>
  <form>
    ...
  </form>
</template>

<script>
import { reactive, toRefs } from '@vue/composition-api'

function useReducer(reducerFn, initialState) {
  const state = reactive(initialState)
  const dispatch = (action) => {
    console.log('dispatching action:', action)
    reducerFn(state, action)
  }
  return [state, dispatch]
}

function reducer(state, action) {
  const { type, payload } = action
  state[type] = payload
}

export default {
  setup() {
    const initialState = {
      taxYear: 2019,
      filingStatus: 'SINGLE',
      income: '75000',
      children: 0,
      stimulusAmount: -1,
    }
    const [state, dispatch] = useReducer(reducer, initialState)

    dispatch({
      type: 'taxYear',
      payload: 2020,
    })
    // state.taxYear === 2020
    return {
      ...toRefs(state),
    }
  },
}
</script>

And according to @dgreene 's question - at first glance, it reduces the amount of written code and simplifies it at all.
Furthermore, It would be easier to deal with initialState if the data structure has changed or has occurred another way to handle the given state or - like in my vue example - we need to add some kind of middleware during dispatching an action (console.log).
Correct me if I am wrong.

Collapse
 
m0nica profile image
Monica Powell

Oooo thanks for sharing your approach in Vue. I agree that useReducer() makes the hooks logic more reusable/DRY than useState() but that both approaches achieve the same thing.