Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 modeExit fullscreen mode

This portion of code will help in the main app

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

2 . Create the increaseCount and decreaseCount functions with dispatch:

const increaseCount = () => {   dispatch({ type: 'increase' });}const decreaseCount = () => {   dispatch({ type: 'decrease' });}
Enter fullscreen modeExit 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 modeExit 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 modeExit 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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A enthusiastac software developer with more experience in the frontend side. Fanatic to create a clean code and the best practices of web/mobile technology prefered angular, react.
  • Location
    Quito, Ecuador
  • Work
    Frontend Software Engineer
  • Joined

More fromjoedev090

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp