DEV Community

roggc
roggc

Posted on

2 1

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay