useReducer() and scale up ReactJs with useContext()

  • 1

  • 1

The useReducer(reducer, state) adds a reducer function to change the state object.

//The reducer function uses (initial) state and (dispatch) action as arguments. 
//some cases return update the state, other replace it with _action_ properties

function reducer(state, action) {
  switch (action.type) {
    case 'incremented_age': {
      return {
        name: state.name,
        age: state.age + 1
      };
    }
    case 'changed_name': {
      return {
        name: action.nextName,
        age: state.age
      };
    }
  }
  throw Error('Unknown action: ' + action.type);
}

const initialState = { name: 'Taylor', age: 42 };
const [state, dispatch] = useReducer(reducer, initialState);

The useReducer() returns the current state and the dispatch update function to re-render the state.

chevron-rightReducer return objectshashtag

The reducer() function doesn't update single properties, it returns new state objects.

An initial state object returned from a function, even if called once, will be re-called each re-render.

We add an initializer function to the useReducer() hook.

Scaling up React components with useContext() and useReducer()

A parent component includes its {children} components as a prop.

We useContext() and useReducer() to manage complex states and event handlers at every component level.

chevron-rightSingle component useContext() and useReducer() hashtag

We createContext() Provider values for the [state, dispatch] of useReducer().

Any imported nested component will have access to both the state and event handler functions.

1

1

1

1

Scaled up useReducer() and useContext()

An useReducer() value used in inline style will need to be parseInt() before, even if it's an integer.

1

1

1

1

1

Last updated