useReducer Hook

useReducer Hook

A Guide to Reducers and the useReducer Hook in React ๐ŸŽฃ

ยท

5 min read

In our previous article, we learned about three important Hooks: useState, useEffect, and useContext hooks. ๐Ÿ˜Š

๐ŸŽฏ In this article, we're going to learn about another hook called useReducer.

Introduction ๐Ÿ“

In a React app, we often need to change or update something, and that's where state comes into play. It's like keeping track of what's happening in your app.

As your app gets bigger and does more things, keeping track of all these changes can get tricky. It's like trying to remember a long list of things to do.

But don't worry! There's a clever way to handle these changes, and it's called reducers. Think of reducers as helpers that make changing state easier. They simplify things when your code gets big and complex.

So, what are reducers, and how do you use them? We'll dive into all of this in this post, including a special tool called the useReducer hook that makes it all possible. Let's get started! ๐Ÿ˜„

What is useReducer๐Ÿค”

useReducer()๐Ÿš€ is a tool in React that helps manage complicated state in your app. It's a bit like using setState, but it follows a pattern similar to Redux (alternative of useReducer and it's a 3rd-party library ) a popular state management library. Instead of directly changing the state, you send actions to a special function called a reducer. This reducer decides how to update the state based on the actions you send.

Why do You Need It โ“

You need a reducer when your application's state management becomes more complex and needs a clear, organized way to handle updates. Reducers provide a structured and predictable approach to managing state changes, making your code easier to understand and maintain as your app grows. In simpler terms, reducers help keep your app's state in order, especially when things get more complicated.

Deciding Between useReducer and useState๐Ÿ”Ž

  • useReducer is like a toolbox for handling complex and connected states. It's best when your state needs lots of special attention and complicated updates, not just simple changes.

  • useState is more like a simple tool for when your states are not complicated and don't rely on each other. It makes your code shorter and easier to understand than using useReducer. ๐Ÿš€

How the useReducer Hook Works ๐ŸŒฒ

Here are the steps for using useReducer :

  1. First, you need to bring in useReducer from React. It's like inviting a special helper to your code party.

     import React, { useReducer } from 'react';
    
  2. The useReducer hook needs two things: a reducer function and an initial state. It's like telling it what to do and where to start.

  3. When you use useReducer, it gives you back two important things: the current state and a function called dispatch. It's like getting two keys to open the state box.

     const [state, dispatch] = useReducer(reducer, initialState);
    
    • state: This is what the useReducer brings you back. It's the current state of your app.

    • dispatch: It's like a messenger you use to make changes to the state. You tell the messenger what to do, and it makes it happen.

    • reducer: This is like a smart helper function that figures out how to change the state based on what you tell it (the action).

    • initialState: It's where you tell your state to start from, like setting the starting point for a game.

Don't worry if it seems a bit confusing at first. In practice, it's not as complicated as it may seem. Let's understand by an example :

// Importing React and the useReducer hook from the 'react' library
import React, { useReducer } from "react";

// Define the initial state for the counter
const initialState = 0;

// Define the reducer function, which handles state changes
const reducer = (state, action) => {
  switch (action) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    case 'RESET':
      return initialState;
    default:
      return state;
  }
}

// Define the Counter component
function Counter() {
  // Use the useReducer hook to manage state using the reducer function and initial state
  const [count, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      {/* Display the current count */}
      <h2> Count is {count} </h2>

      {/* Buttons to trigger the 'INCREMENT', 'DECREMENT', and 'RESET' actions */}
      <button onClick={() => dispatch('INCREMENT')}>Increment</button>
      <button onClick={() => dispatch('DECREMENT')}>Decrement</button>
      <button onClick={() => dispatch('RESET')}>Reset</button>
    </>
  );
}

// Export the Counter component
export default Counter;

In this example, useReducer is used to manage the count state. However here if you use useState then also it is going to be fine. Because useReducer is more beneficial when you have more complex state logic or when you need to manage multiple pieces of state that interact in intricate ways. It provides a structured way to handle state updates and can make your code more maintainable as your application grows.

So, the choice between useState and useReducer depends on the complexity of your state management. For simple, straightforward state updates(like the above example), useState is sufficient. However, when dealing with complex, interconnected state, useReducer offers a more organized and manageable approach.

Conclusion ๐Ÿ’ฅ๐Ÿ™Œ

In summary, useReducer makes it easier to manage complicated states in React. It keeps your code organized and easy to maintain as your app gets bigger. It's especially helpful when dealing with complex state situations, making your code work better.


Thanks for reading all the way to the end! ๐Ÿ’–

If you have any questions, please use the comments section ๐Ÿ’ฌ

Let's connect! Find me on the web ๐Ÿ”—

If you have any Queries or Suggestions, feel free to reach out to me.

Happy Coding :)โค๏ธ

Did you find this article valuable?

Support Kushal Das by becoming a sponsor. Any amount is appreciated!

ย