useReducer Hook

Basic concept of reducers

function reducer(state, action) {
return state + action
}

Example of useReducer

const [state, dispatch] = useReducer((state, action) =>{
switch(action.type) {
case 'LOAD_POKEMON': {
return { ...state, pokemon: aciton.name, img: action.img }
}
case 'ERROR': {
return { ..state, error: action.error}
}
case 'CASSIDY': {
return { ...state, pokemon: action.pokemon }
}
default: {
return state
}
}
}, {
// initial state object
pokemon: 'pika',
img: null,
error, null
})
let { pokemon, img, error } = state
.
.
.
<input
onChange={(event) => {
dispatch({type: 'CASSIDY', pokemon: event.target.value })
}}
value={pokemon}
type="text"
/>
  • can use useState and useReducer in same component
  • fun fact - useState is implemented with useReducer
  • can make full on state machine to call other functions
  • not just change state, but it can call function to do side effects