useReducer in React

useReducer in React

The useReducer Hook is a react hook that allow management state in react. the useState hook is great for simple state changes, useReducer is suitable for complex state changes. useReducer takes two argument reducer function and the initial state. The reducer function takes the current state and action, and return a new state based on action type.

Example:

import React, { useReducer } from 'react'

const reducer = (state, action) => {
    switch (action?.type) {
        case "increment":
            return { count: state?.count + 1 }
        case "decrement":
            return { count: state?.count - 1 }
        default:
            return state
    }
}

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

    return (
        <div>
            <p>Count : {state?.count}</p>

            <button onClick={() => {
                dispatch({ type: "increment" })
            }}>Increment</button>

            <button onClick={() => {
                dispatch({ type: "decrement" })
            }} >Decrement</button>
        </div>
    )
}

export default App

The dispatch function is used to send an action to the reducer. To increment the count, you should call dispatch({ type: 'increment' }). To decrement the count, you should call dispatch({ type: 'decrement' }).