Monday, May 22, 2023

How to use useDispatch and useSelector? React Hooks Example Tutorial

Hello guys, if you are learning about React hooks and wondering how to use useDispatch and useSelector hooks in React application then you have come to the right place. Earlier,, I have shared the best React courseswebsites, and books and in this article, I am going to show you how React hooks make coding and statement management easier than it was before. The introduction of React hooks changed a lot in the react application development. Developers moved from complicated and length class-based components to simpler functional components that can do the same work in fewer lines of code. 


Apart from React hooks, React also introduced redux hooks. Redux is a third-party library used to manage the state of a complex and huge react application. It is, by far, the most popular third-party state management library. 

Redux is always considered complicated. To ease the working with redux, react provided two simple but powerful hooks - useDispatch and useSelector.

 These two hooks eliminate the use of the complicated connect() method. In this article, we will discuss what are useDispatch and useSelector hooks and how can we use them in a react application to manage the state.

By the way, this is the 5th article in my series of React for Java developers. Earlier, I have shared how to do state management in ReactWhat is Redux and why use itlifecycle methods on functional components, and useState hooks example etc.

And in this article, you will learn about the useDispatch and useSelector hooks with real-life examples to write better and cleaner React code. I highly recommend every React developer to learn about hooks as it can simplify your code and makes it more maintainable. 





What are useDispatch and useSelector hooks in React.js?

Earlier the connect() method was used to read the state from the redux store. It has two optional arguments, mapStateToProps and mapDispatchToProps, and these two arguments are used to work with the redux. But they are complicated and require a lot of effort to understand. 

Now, react provides a better alternative to the connect() method and its arguments. 

The useDispatch and useSelector hooks are alternatives to mapDispatchToProps and mapStateToProps, respectively. 

The useDispatch hook is used to dispatch an action while useSelector hook is used to get the state from the redux store. Let’s understand these two hooks with the help of an example. 

Observe the following code.

import "./styles.css";

import Display from "./Display";

import Button from "./Button";

export default function App() {

  return (

    <div className="App">

      <Button />

      <Display />

    </div>

  );

}

The above file has two components in the JSX - Button, and Display. 

With every click of the button, the value below should increment by 1. For this, we have to install redux and implement store, action, and reducer.

Following is the action:

const increment = {

  type: "INCREMENT"

};

export default increment;


Following is the reducer:

const counter = (state, action) => {

  if (action.type === "INCREMENT") {

    return {

      ...state,

      value: state.value + 1

    };

  }

  return state;

};

Whenever the action is dispatched, the reducer increments the “value” by 1.

Following is the store:

import { createStore } from "redux";

import counter from "./reducer";

const initialState = { value: 0 };

const store = createStore(counter, initialState);

export default store;


We have the redux setup. Now we will use the react-redux hooks to dispatch the action in the Button component and update the state in the Display component.

How to use useDispatch and useSelector? React Hooks Example Tutorial


Let’s start with the Button component.

import { useDispatch } from "react-redux";

import increment from "./action";

function Button() {

  const dispatch = useDispatch();

  const handleClick = () => {

    dispatch(increment);

  };

  return (

    <div>

      <button onClick={handleClick}> Click here </button>

    </div>

  );

}

export default Button;





Observe the following line of code.

const dispatch = useDispatch();

The useDispatch hook returns a function. So it is assigned to a variable. Then, in the “handleClick” function, it is used to dispatch the “increment” action.

const handleClick = () => {

    dispatch(increment);

  };

Now, whenever the button is clicked, the “value” in the state is incremented by 1. But as of now, it does not update the value in the Display component. To make it display the value accordingly, we need to access the state using the useSelector hook. 

import { useSelector } from "react-redux";

function Display() {

  const value = useSelector((state) => state.value);

  return (

    <div>

      <p> {value} </p>

    </div>

  );

}

export default Display;


Observe the following line of code.

const value = useSelector((state) => state.value);


Here, the useSelector hook is used to extract “value” from the global state. We can take out any state we want to use in the component using the same way. 

So now when the button is clicked, the value below it will be incremented by 1. This is how useDispatch and useSelector hooks are used in react.


That's all about how to work with useDispatch and useSelector hooks in React.js. Redux is an essential part of a complex and huge react application because managing the global state in such applications is difficult. If you have ever worked with redux, you know it is not easy to use it.

Redux is complicated. The useDispatch and useSelector hooks make the work easy. The useDispatch hook lets us efficiently dispatch actions while the useSelector hook gives us access to the global state anywhere in the application. These hooks are easy to understand and even easier to use.

   Other React and development Articles and resources you may like


Thanks for reading this article so far.  If you like this React hooks tutorial and examples of useSelector and useDispatch hooks, then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a comment.

P. S. - If you want to learn React.js from scratch and looking for free React courses to learn concepts like components, virtual DOM, etc then I also recommend you to join these free online REact.js courses for beginners. It contains free courses from Udemy, Coursera, edX to learn to React online for FREE.  

1 comment: