Dispatching actions and accessing state with useSelector and useDispatch in React JS

Redux is a powerful state management tool for React that helps to manage the global state of an application in a predictable manner. In a React-Redux setup, you can access and manipulate the Redux store using hooks like useSelector and useDispatch.

In this article, we will explore how to use useSelector to access the Redux state and useDispatch to dispatch actions to modify that state.

1. Overview of useSelector and useDispatch

- useSelector: This hook allows you to extract data from the Redux store by selecting a piece of state. It is similar to the mapStateToProps function used in class components.

- useDispatch: This hook gives you access to the dispatch function, which allows you to send actions to the Redux store to trigger state changes.

2. Setting Up Redux Store

Before using useSelector and useDispatch, you need to set up the Redux store and the necessary reducers. Let's start by creating a simple store with a reducer to manage a counter value.

Example 1: Setting Up Redux Store

        
          import { createStore } from 'redux';

          const initialState = { count: 0 };

          const counterReducer = (state = initialState, action) => {
            switch (action.type) {
              case 'INCREMENT':
                return { count: state.count + 1 };
              case 'DECREMENT':
                return { count: state.count - 1 };
              default:
                return state;
            }
          };

          const store = createStore(counterReducer);
        
      

In the example above, we created a simple Redux store with a counterReducer. The reducer handles two actions: INCREMENT and DECREMENT, which modify the count state.

3. Providing the Redux Store to the Application

Next, you need to wrap your application with the Provider component from react-redux to provide the Redux store to your React components.

Example 2: Wrapping the App with Provider

        
          import React from 'react';
          import ReactDOM from 'react-dom';
          import { Provider } from 'react-redux';
          import { createStore } from 'redux';
          import App from './App';

          // Counter reducer and store creation
          const initialState = { count: 0 };
          const counterReducer = (state = initialState, action) => {
            switch (action.type) {
              case 'INCREMENT':
                return { count: state.count + 1 };
              case 'DECREMENT':
                return { count: state.count - 1 };
              default:
                return state;
            }
          };
          const store = createStore(counterReducer);

          // Rendering App with Provider
          ReactDOM.render(
            
              
            ,
            document.getElementById('root')
          );
        
      

Here, the Provider component wraps the entire application, ensuring that all components inside the App have access to the Redux store.

4. Accessing State with useSelector

The useSelector hook allows your components to access the state stored in Redux. It takes a selector function that returns the part of the state you are interested in.

Example 3: Using useSelector to Access Redux State

        
          import React from 'react';
          import { useSelector } from 'react-redux';

          const CounterDisplay = () => {
            const count = useSelector(state => state.count); // Access count from Redux store

            return 

Count: {count}

; }; export default CounterDisplay;

In the example above, we use useSelector to access the count value from the Redux store. The state parameter in the selector function refers to the entire Redux state, and we return the count property from it.

5. Dispatching Actions with useDispatch

The useDispatch hook allows you to dispatch actions to modify the state in the Redux store. It returns a reference to the dispatch function, which you can use to dispatch actions.

Example 4: Using useDispatch to Dispatch Actions

        
          import React from 'react';
          import { useDispatch } from 'react-redux';

          const CounterControls = () => {
            const dispatch = useDispatch();

            const increment = () => {
              dispatch({ type: 'INCREMENT' });
            };

            const decrement = () => {
              dispatch({ type: 'DECREMENT' });
            };

            return (
              
); }; export default CounterControls;

In the above example, we use useDispatch to get access to the dispatch function. We create two functions: increment and decrement, which dispatch INCREMENT and DECREMENT actions to the Redux store.

6. Complete Example with Dispatching and Accessing State

Now let’s combine both useSelector and useDispatch in a simple component where we can display and update the count.

Example 5: Full Counter Component

        
          import React from 'react';
          import { useSelector, useDispatch } from 'react-redux';

          const Counter = () => {
            const count = useSelector(state => state.count); // Accessing state
            const dispatch = useDispatch(); // Dispatch function

            const increment = () => {
              dispatch({ type: 'INCREMENT' });
            };

            const decrement = () => {
              dispatch({ type: 'DECREMENT' });
            };

            return (
              

Count: {count}

); }; export default Counter;

In this full example, the Counter component displays the current count from the Redux store using useSelector. It also dispatches INCREMENT and DECREMENT actions using useDispatch when the buttons are clicked.

7. Conclusion

Redux hooks like useSelector and useDispatch make it easy to manage and update application state in React. useSelector allows you to access parts of the Redux store’s state, while useDispatch allows you to dispatch actions to update that state. These hooks make Redux usage in React applications more efficient and cleaner by removing the need for the connect function.

By mastering these hooks, you can handle more complex state management scenarios in your React applications and build scalable, maintainable projects.





Advertisement