DEV Community

Cover image for useReducer hook in React (No redux here)
Clara Situma
Clara Situma

Posted on

useReducer hook in React (No redux here)

The useReducer is a hook that provides a way to manage state in a React component.

Is it dependant on redux?

No, it's provided by React and can be used independently of Redux.

useReducer is a way to manage state within a single React component, whereas Redux is a state management library that is used to manage state in larger applications.

While useReducer and Redux share some similarities, they are not required to be used together. You can use useReducer on its own in a React component, or you can use Redux to manage state in an application that includes multiple components.

clara_situma_useReducer

More on useReducers

It is similar to the useState hook, but it allows you to manage more complex state logic and handle multiple state updates with a reducer function.

To use useReducer, you first need to define a reducer function that takes in the current state and an action, and returns a new state.

Then, in your component, you can call useReducer and pass in the reducer and an initial state. This returns an array with the current state and a dispatch method, which you can use to trigger state updates by calling the dispatch method and passing in an action.

Here is an example of using useReducer in a React component:



import {useReducer}from 'react'

const initialState = {
  count: 0,
};

/////takes in the current state and an action, and **returns a new state.**/updates state

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
};

function MyComponent() {
//call useReducer and pass in the reducer and an initial state

  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>
        Increment
      </button>
      <button onClick={() => dispatch({ type: "decrement" })}>
        Decrement
      </button>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

In this example, the useReducer hook is called with the reducer function and the initialState object.

This returns the state object and a dispatch method, which is used to trigger state updates by calling dispatch and passing in an action object. The state object contains a count property that is incremented or decremented when the corresponding buttons are clicked.

Top comments (8)

Collapse
 
pgrepds profile image
David Scholz

Thanks for this article. So the useReducer hook is like useState but allowing a more complex setter functionality, right? Redux is a global state management and allows us to reuse a state in multiple components. If I have understood your article correctly, then useReducer is still a local state. In the above example, I do not see the benefit of using useReducer instead of useState. The dispatch logic could be easily implemented using a normal state and some sort of handleOnClick function that sets the state depending on the type parameter. The code would look almost identical. Where exactly is the benefit when not using redux?

Collapse
 
csituma profile image
Clara Situma • Edited

Hey David,
You're quite right

In this example , using useReducer would not provide a significant benefit compared to using useState. However, in larger applications with more complex state management needs, useReducer can provide a more scalable and maintainable approach to state management.

One of the benefits of using useReducer over useState is that it allows for a more modular and reusable approach to state management., another one would be that it could be better in cases where two related states are depending on current state

With useState, each component would need to implement its own logic for updating the state, which can lead to code duplication and a lack of consistency. With useReducer, you can define a single reducer function that can be used by multiple components, allowing for more consistent and maintainable state management.

Collapse
 
pgrepds profile image
David Scholz

Thank you for your response. I agree with you. The reusability aspect is indeed a good argument. Do you think that it is beneficial to implement this directly in a custom hook then? What bothers me is that we need to import the dispatcher function in every component in which we want to use the same reducer. We could also encapsulate this logic in a custom hook and this hook exports a state and a function that is pretty much identical with the dispatch function. No code duplications and we could reuse this easily as well. However, we won't need the useReducer hook in the first place then. I guess that I'm missing something here.

Thread Thread
 
csituma profile image
Clara Situma • Edited

You definitely are making alot of sense and are correct. Thanks for your comment

In general, useState is a simpler and more straightforward way to manage local state in a React component and so there is very few instances where useReducer would be preferred over it for managing local state in a React component.

I would think the useReducer's true advantage over usestate on managing local state is that it's easier to test and more readable and efficient than a usestate callback in examples of manageing state that is dependent on the previous state, and in managing multiple related state values. usestate could sometimes be buggy in the latter

However, the essense of this article was understanding useReducer and showing instances of how it could be used without redux, without really getting into the nitty gritty of specifics of whether or not it should be used for local state management and comparing it to usestate.

here's a good piece for comparisons, and with examples
kentcdodds.com/blog/should-i-usest...

Thread Thread
 
pgrepds profile image
David Scholz

Makes sense, I will definitely check this hook out in some project. Thanks for the discussion and this nice article :).

Thread Thread
 
csituma profile image
Clara Situma • Edited

Thank you as well for your very much needed contribution.

Collapse
 
jankapunkt profile image
Jan Küster

I would also add that you can inject the dispatch methods into child components, allowing them to update the parent state.

Collapse
 
csituma profile image
Clara Situma • Edited

Yes ofcourse :)