React hooks useReducers()
Harry J Beckwith

Harry J Beckwith @hjames

Joined:
Feb 14, 2019

React hooks useReducers()

Publish Date: Aug 19 '21
3 1

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

Comments 1 total

  • ScriptKavi
    ScriptKaviJul 25, 2024

    Many early birds have already started using this custom hooks library
    in their ReactJs/NextJs project.

    Have you started using it?

    scriptkavi/hooks

    PS: Don't be a late bloomer :P

Add comment