02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Dispatching Actions and Updating React

Dispatching Actions and Updating React

In this tutorial, we will explore the process of dispatching actions in Redux and updating React accordingly. We will go step by step through the different phases of this process, including rendering data and subscribing to store changes. By the end of this tutorial, you will have a clear understanding of how to manage application state effectively and keep your React UI in sync with Redux.

Introduction

Redux is a powerful state management tool commonly used with React. It allows you to centralize your application's state and easily manage how data flows through different parts of your app. Dispatching actions is a fundamental concept in Redux that helps in updating the state, which is then reflected in the React components.

In this tutorial, we will:

  1. Understand what actions are and how they are used in Redux.
  2. Learn how to dispatch actions to modify the store.
  3. Connect Redux and React to keep the UI in sync with state changes.
  4. Explore how React can subscribe to Redux store changes to ensure updates are reflected in the UI.

Step 1: Understanding Actions and Dispatch

What Are Actions?

Actions in Redux are plain JavaScript objects that describe an event that has occurred. They are the only source of information for the store. An action must have a type property that tells the reducer how to interpret the action and optionally, some payload data that specifies what needs to be done.

For example:

const incrementAction = {
    type: 'INCREMENT'
};

How to Dispatch Actions

Dispatching an action means sending it to the Redux store, which then updates the state accordingly. You can dispatch actions by using the dispatch() method provided by Redux.

Here's an example of dispatching an action:

store.dispatch(incrementAction);

In this example, the incrementAction is dispatched, and the Redux store will handle it according to the reducer logic.

Step 2: Connecting Redux to React

To make Redux interact seamlessly with React, we need to ensure that React components can send actions to the Redux store and access the updated state.

Setting Up the Store

First, create a Redux store that will hold the state of your application. You can use createStore() to create the store and provide a reducer function:

import { createStore } from 'redux';

const initialState = {
    count: 0
};

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

const store = createStore(reducer);

Connecting React and Redux with Provider

To connect React with Redux, use the Provider component from react-redux. This component makes the Redux store available to all components within your app.

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

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

Step 3: Rendering Redux State in React Components

Once the store is connected to the app, components can access the state using the useSelector hook from react-redux.

Using useSelector

The useSelector hook allows components to read values from the Redux store:

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

const Counter = () => {
    const count = useSelector((state) => state.count);
    return (
        <div>
            <h1>Count: {count}</h1>
        </div>
    );
};

export default Counter;

Step 4: Dispatching Actions from React Components

To update the state from a React component, you need to dispatch actions. This is done using the useDispatch hook.

Using useDispatch

The useDispatch hook provides access to the dispatch function, allowing you to send actions to the Redux store:

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

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

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

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

    return (
        <div>
            <button onClick={handleIncrement}>+</button>
            <button onClick={handleDecrement}>-</button>
        </div>
    );
};

export default Controls;

Step 5: Subscribing to Store Changes

By default, when the Redux store changes, the connected React components will re-render. However, sometimes you need to subscribe explicitly to see how changes are reflected in the UI.

To achieve this, you can use the subscribe method on the Redux store, though this is generally managed by the Provider component.

Here's a simplified example of using subscribe to re-render manually:

const render = () => {
    console.log(store.getState());
};

store.subscribe(render);

This will log the current state to the console whenever it changes.

Conclusion

In this tutorial, we covered how to dispatch actions and update React using Redux. We walked through the basics of setting up Redux, dispatching actions, connecting it with React, and managing subscriptions to reflect changes.

This workflow ensures that your React components always have access to the latest state from Redux, which helps maintain predictable and consistent behavior throughout your application.

In the next tutorial, we'll dive into more advanced concepts, such as middleware and asynchronous actions, to extend the capabilities of your Redux store. Stay tuned and keep building!

Video Transcript

00:02Let's take a step deeper
00:03and let's talk about dispatching actions and updating React.
00:07Now, to do that, we're gonna take a look at actions
00:09and understand what they are.
00:11We're going to look at how to dispatch those actions.
00:14And last but not least, we also wanna make sure our React
00:16is subscribed to those changes.
00:18So whenever it changes actually happens,
00:21our application will refresh.
00:22But literally the steps involved are,
00:24first there is an action that is triggered
00:26by our React application.
00:28It's dispatch, it's it then reaches our store.
00:32Our store makes the change through the help
00:34of reduction and it's reducers.
00:36And once the change completed, if something is listening
00:40to it, in our case we're gonna add our React application
00:42to listen to those changes.
00:44Then it will update. So it's a one way directional channel.
00:47Let's, let's see it in action.
00:49Alright, in the last lecture we connected our data
00:53by going into our index, loading up our store,
00:56sending our current state as our data property,
00:59and then going into our application itself
01:01and sending to the our counter the specific data
01:04that it relates to it.
01:06Now I'm just gonna go ahead here instead of,
01:08let me just change that to Redux
01:10and let's move on to 2.2 just so we're up to date.
01:13Okay, beautiful. And let's go into our counter
01:15and continue down the process.
01:17So first of all, we want to re-Jigger up set up.
01:20And we also wanna step up
01:22and we also wanna jigger step down.
01:24Now the way we're gonna do that is,
01:27and by the way, if you recall,
01:28when we were working on our store test,
01:30we created all these different tests
01:32where we were basically dispatching our store.
01:35And that's exactly what we're going to do next.
01:38So literally, I'm gonna go into my counter
01:40and I'm gonna go ahead and import our store.
01:43I'm also gonna import the step up
01:47and my step down.
01:51And that's gonna be from our current folder.
01:54Step one folder back.
01:55Well you could just step one folder back
01:58and grab from there.
01:59Our store. Beautiful.
02:01All that's left for us to do is literally do that.
02:04Dispatch, man. So I could literally just grab the store
02:07dispatch and I'm just gonna put it right into our counter,
02:10deleting our state here.
02:12And there we go. Store, step Up has been dispatched,
02:15store Step Down has been dispatched.
02:17Now we're only gonna have one last item
02:20that we're gonna need to sort out.
02:21And that is if we just try to test things out right now
02:24and we click here on the plus
02:25and the minus, we're not gonna actually see the
02:28changes going on.
02:29The reason is, is because although the data is changing
02:32and it really is changing, our store is getting updated,
02:36it's actually not reflecting in our rendering.
02:39'cause our rendering is only taking our state once
02:41and never taking it further ever again.
02:45So to address that problem,
02:46I'm literally just gonna grab our rendering method
02:50and I'm just gonna create here a new function called
02:52Render Render.
02:56And I'm just gonna go ahead
02:57and send inside of it our original call.
03:01And first of all, I'm gonna just by default make sure
03:03that I call it at least once.
03:05So let me just go ahead and call our render.
03:11Last but not least, remember we
03:12got a reference to that store.
03:13So it's time for us to go to that store and tell it.
03:15By the way, anytime there is an update, I wanna subscribe.
03:21And that is our third variable, our third method really.
03:25And last one in the core methods of Redux,
03:28where I'm literally just gonna send in a method.
03:30And that method or function for
03:32that matter will be called each time our rendering,
03:37our each time our store has an update
03:40and something dispatches inside of that update once
03:43that update completes.
03:44So let's go ahead and save this
03:46and it's time for us to test it out.
03:47And we should see now, uh, if we don't, sub
03:50scribe is not a function.
03:51So let me just double, triple, quadruple sub,
03:57I'm missing subscribe.
04:02And now if I go ahead
04:03and I click here on my Plus, you'll see
04:05that my counter is going up and my counter is going down.
04:08Obviously we want a better solution
04:10than all of our counters.
04:11The same thing, which is something we'll address in the next
04:14lecture, but
04:15for now we got ourselves a fully working counter.
04:19Now I wanna just walk through the steps, all of the steps
04:21that we've done so far in connecting things.
04:24So step number one is we're
04:26separating our rendering function.
04:27So it could re-Render once.
04:29It could re-render, we're subscribing it to our store,
04:33making sure that anytime our store changes,
04:35it will call our render function.
04:38Our render function will then re-render our full React
04:42component, our full application really for that matter.
04:45And as it does, so it's gonna send the current state into
04:47our data property.
04:51Our application itself is gonna fetch that data,
04:54do something with it in most probability.
04:56But in our case, it's just taking that data as is
04:59and sending it into our counter the same data three times,
05:02which is why our counter shows all three counters
05:05show the same information.
05:07Last but not least, our counter actually takes that data
05:11and adds it into its item.
05:13And whenever a click happens, if it's a click up,
05:16it will dispatch from the store itself a step up.
05:20If it's a down, it will dispatch a step down.
05:22Now in our store itself,
05:24what is actually happening is our store itself.
05:28What's actually, by the way, I moved things around just
05:30so not to get warnings,
05:31but I just moved all of our exports to the top
05:33because they're using the counter.
05:36And I just wanted everything to be organized together.
05:39Um, it wouldn't create any errors,
05:41but it was creating a warning, telling me
05:42that I'm using our counter before it's actually defined
05:46or I'm using the step up
05:48before it was defined 'cause it was on the bottom.
05:50So I moved it up to the top.
05:52So now what is happening inside of our store?
05:54So once a store is wrapped,
05:56it will automatically call our counter and our counter.
06:00If it's a step up, we'll basically take whatever the value
06:02is currently there, which is zero in our case,
06:05and then bump it up to 1, 2, 3, or bump it down.
06:09And if it's called without making any change,
06:10it's gonna send in whatever the current value is
06:13because the store itself will send in
06:16to the counter the latest value.
06:18If one doesn't exist, it won't send anything.
06:20But that would then return back as zero,
06:22because zero is our default.
06:24Now we're gonna take a look at much more complex creations,
06:29not that far from now, but for now that covers the basics.
06:32Basics of how to work with Redux.
06:35And in the next lecture we're gonna take it a step further
06:37because we're gonna solve our problem of having all
06:40of these counters connected when we really want a separate
06:43counter for each one of our components.
06:47In this lecture, we really completed the core steps of
06:50inter integrating between React and Redux.
06:53In the next lecture, we'll continue down the path
06:56of making our reducers more complex
06:58by upgrading our reducer from just being a number into being
07:02an actual array.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!