useReducer Is a hook in React that is used for managing the state in a functional component. It is similar to useState, but is more powerful and can be used for managing more complex state changes.
Here's how useReducer works:
Here's an example of how you might use useReducer in a React component:
In this example, we have a counter that increments and decrements based on the actions dispatched by the buttons. The reducer function is responsible for updating the state based on the actions.
Because of the way useReducer
works, we can change it into something flexible.
I tend to use this if my component has a lot of states that belong together.
It's cleaner than useState
with an object.
import {useReducer} from 'react'
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1}
case 'decrement':
return {count: state.count - 1}
default:
throw new Error()
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, {count: 0})
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
)
}
import * as React from 'react' // import React and its hooks
const initialState = {
// store initial state
key: 'value',
}
function Component() {
const [store, setStore] = React.useReducer(reducer, initialState) // useReducer hook
function updateStore(values) {
// update store function
setStore(values)
}
return <div />
}
function reducer(state, newState) {
// reducer function to update store
return {...state, ...newState}
}