DEV Community

roggc
roggc

Posted on

useReducer Hook Use Cases In React

I want to present you in this post some use cases for useReducer hook.

These are three.

Toggle

When we want to toggle state, being state a boolean, we can do:

import {useReducer} from 'react'

export const useToggle= (initialState=false)=>{
  const [isSomething, toogleIsSomething]= useReducer(state=> !state, initialState)
  return [isSomething,toggleIsSomething]
}
Enter fullscreen mode Exit fullscreen mode

So whenever we want to use this hook we can do:

function SomeComponent(){
  const [isSome, toogleIsSome]=useToggle()
  return ...
}

export default SomeComponent
Enter fullscreen mode Exit fullscreen mode

Update

Another use case is when we want to update state, we can do so:

import {useReducer} from 'react'

export const useUpdate= (initialState={})=> {
  const [state, updateState]= useReducer((state, obj)=>({...state, ...obj}), initialState)
  return [state, updateState]
} 
Enter fullscreen mode Exit fullscreen mode

We can use it like this:

function AnotherComponent(){
  const [state, updateState]= useUpdate({c:3})

  const someHandler= ()=>{
    updateState({a:1,b:2}) // after that state will be {a:1, b:2, c:3}
  }

  return ...
}

export default AnotherComponent
Enter fullscreen mode Exit fullscreen mode

Dispatch

Then we have the typical use case where we pass an action as a second parameter to the reducer function and we get a dispatch function as a result:

const reducer=(state, action)=>{
  switch(action.type){
    case 'UPDATE':
      return {...state, ...action.payload}
    default:
      return state
  }
}

function ThirdComponent(){
  const [state, dispatch]= useReducer(reducer,{c:3})

  const someHandler= ()=> {
    dispatch({type:'SOMETHING', payload: {a:1, b:2}})
  }


  return ...
}

export default ThirdComponent
Enter fullscreen mode Exit fullscreen mode

If you come with another use case not presented in this post please it would be nice if you leave it in the comments.

Thanks.

Top comments (0)