Coding task · JavaScript and React course · Module 4: Context API and useReducer

Practice: useReducer Basics

useReducer for complex state: const [state, dispatch] = useReducer(reducer, initialState). Reducer: (state, action) => switch(action.type) { case 'INCREMENT': return {...state, count: state.count + 1} }. Dispatch: dispatch({ type: 'INCREMENT' }).

Task

Create a reducer for energy: initialState = { engines: 50, shields: 30, weapons: 20 }. Actions: BOOST_ENGINES (+10), BOOST_SHIELDS (+10), BOOST_WEAPONS (+10). dispatch({ type: 'BOOST_ENGINES' }). Display all values!