DEV Community

Cover image for ReactJS Design Pattern ~Reducer Pattern~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Design Pattern ~Reducer Pattern~

・Reducer Pattern can be used when you have multiple states depending on complex logic. If you utilize this pattern, you update the state via a reducer function to update the state instead of updating the state directly. In the component, you dispatch an action type and then update the state.

import React, { useReducer } from 'react'
import { State, Action } from '@type/index'

const initialState = {
  count: 0,
}

const reducer = (state: State, action: Action) => {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + 1 }
    case 'decrement':
      return { ...state, count: state.count - 1 }
    default:
      return state
  }
}
export const Counter = () => {
  const [state, dispatch] = useReducer(reducer, initialState)
  return (
    <div>
      <p>カウント: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increase</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrease</button>
    </div>
  )
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)