DEV Community

Harry J Beckwith
Harry J Beckwith

Posted on

React hooks useReducers()

Can be used as a replacement for useState, if you need more "powerful state management".

More complex to use and requires more set up than useState.

Majority of the time useState is used.

returns an array with two values, array de structuring is good to use here.

const [state, dispatchFn] = useReducer(reducerFn, initialState, initFn)
Enter fullscreen mode Exit fullscreen mode

state = state snapshot used in the component.

dispatchFnc = a function that can be used to dispatch a new action e.g trigger an update of the state.

reducerFn = A function that is triggered automatically once an action is dispatch (via dispatchFn()) - it receives the latest state snapshot and should return the new updated state.

initialState = The initial state

initFn = A function to set the initial state

Example...


// create reduction fnc stored input goes into state
const emailReducer = (state, action) => {
  if(action.type === 'USER_INPUT') {
    return { 
      value: action.val, 
      isValid: action.val.includes('@') 
    }
  }
  return {value: '', isValid: false}
}
//creating a reducer. dispatch email fnc that calls email reducer which updates the state (emailState)

const [emailState, dispatchEmail] = useReducer(emailReducer, { value: '', isValid: null })

// calling the dispatch with updated input
 const emailChangeHandler = (event) => {
    dispatchEmail({ type: 'USER_INPUT', val: event.target.value })

  };
Enter fullscreen mode Exit fullscreen mode

Top comments (0)