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]
}
So whenever we want to use this hook we can do:
function SomeComponent(){
const [isSome, toogleIsSome]=useToggle()
return ...
}
export default SomeComponent
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]
}
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
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
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.