Skip to main content

useReducer

The useReducer hook is similar (in functionality) to the useState hook. It allows for custom state logic. If you find yourself keeping track of multiple pieces of state that rely on complex logic, useReducer may be useful.

Example

import { useState, useReducer } from 'react'

const reducer = (state, action) => {

switch(action.type) {
case "increment": {
return( { count: state.count + action.payload.increment })
}
case "decrement": {
return( { count: state.count - action.payload.decrement })
}
default: return(state)
}
}

const App = () => {

const initialState = { count: 0 }
const [state, dispatch] = useReducer(reducer, initialState )

return(
<div>
<h3>state: { state.count }</h3>
<code style={{ margin: 40 }}>
{ JSON.stringify(state) }
</code>
<div style={{ padding: 40 }}>
<button onClick={ () => dispatch({ type: "increment", payload: { increment: 100 } }) }>Plus</button>
<button onClick={ () => dispatch({ type: "decrement", payload: { decrement: 50 } }) }>Min</button>
</div>
</div>
)
}

export default App;

Breakdown

  • line 3 - 14: a reducer function is created. Best practice is to call it with a action.type-string literal.
  • line 19: the useReducer hook is fired up and gets that reducer function and an initial state as argument.
  • line 28, 29: the reducer is dispatched with the type and the payload (can be a complex object)