DEV Community

joedev090
joedev090

Posted on

Hooks behind the scene 4, UseReducer

Hey coders!!!

In this new post of react, we will check other useful hook...

UseReducer.-

👉🏻 If you find yourself keeping track of multiple pieces of state that rely on complex logic.

  • Manage complex state in react apps
  • Works like a state management (Redux, etc).

The basics:

👉🏻 useReducer(reducer, initialState)

The reducer function contains your custom state logic and the initialState can be a simple value but generally will contain an object.

The useReducer Hook returns the current state and a dispatch method.

👉🏻 As always the best way to learn is with some code.

The result of this code will be:

Image description

We can see the popular count with two buttons, increase and decrease.

1 . Let's begin with a initial state and the reducer function.

const initialState = {count: 0};
const reducer = (state, action) => {
    switch (action.type) {
        case 'increase':
            return { count: state.count + 1 }

        case 'decrease':
            return { count: state.count - 1 }

        default:
            return state;
    }

}
Enter fullscreen mode Exit fullscreen mode

This portion of code will help in the main app

const [state, dispatch] = useReducer(reducer, initialState);
Enter fullscreen mode Exit fullscreen mode

2 . Create the increaseCount and decreaseCount functions with dispatch:

const increaseCount = () => {
   dispatch({ type: 'increase' });
}

const decreaseCount = () => {
   dispatch({ type: 'decrease' });
}
Enter fullscreen mode Exit fullscreen mode

3 . Finally the return part:

return (
    <>
      <h2>Count: {state.count}</h2>
      <button onClick={increaseCount}>Increase</button>
      <button onClick={decreaseCount}>Decrease</button>
    </>
  );
Enter fullscreen mode Exit fullscreen mode

We are showing two buttons and after clicked the increaseCount and decreaseCount will be executed.

For task we can add some improvements like create an object for 'increase' and 'decrease' strings.

Here you have the full version of code:

import { useReducer } from "react";

const ACTION = {
  INCREASE: "increase",
  DECREASE: "decrease",
};

const initialState = { count: 0 };
const reducer = (state, action) => {
  switch (action.type) {
    case ACTION.INCREASE:
      return { count: state.count + 1 };

    case ACTION.DECREASE:
      return { count: state.count - 1 };

    default:
      return state;
  }
};

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const increaseCount = () => {
    dispatch({ type: ACTION.INCREASE });
  };

  const decreaseCount = () => {
    dispatch({ type: ACTION.DECREASE });
  };

  return (
    <>
      <h2>Count: {state.count}</h2>
      <button onClick={increaseCount}>Increase</button>
      <button onClick={decreaseCount}>Decrease</button>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

Conclusion:

  • We will use useReducer to manage complex states in react applications.

  • For simple applications we can use useContext or other ways to manage the state.

Let me know if this post is useful for you and also if you want to check in the same the rest of hooks missing.

Have a great day for coding :D

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️