Flexible useReducer in Reactjs
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:
- You pass useReducer a reducer function and an initial state value.
- The reducer function is a pure function that takes in the current state and an action and returns the new state based on the action.
- useReducer Returns an array with two elements: the current state and a dispatch function.
- You can call the dispatch function with an action, which will trigger the reducer function and update the state.
Here's an example of how you might use useReducer in a React component:
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></>)}
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 * as React from 'react' // import React and its hooksconst initialState = {// store initial statekey: 'value',}function Component() {const [store, setStore] = React.useReducer(reducer, initialState) // useReducer hookfunction updateStore(values) {// update store functionsetStore(values)}return <div />}function reducer(state, newState) {// reducer function to update storereturn { ...state, ...newState }}