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:

  1. You pass useReducer a reducer function and an initial state value.
  2. 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.
  3. useReducer Returns an array with two elements: the current state and a dispatch function.
  4. 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:

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.