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

Integrating Redux

Integrating Redux: Creating a Store and Using getState and dispatch

The time to incorporate the Redux library is now. In this lecture, we will create our store using the createStore function from the Redux library. Once our store is set up, we will use the getState method to access its state and trigger new actions through the dispatch method. By the end of this lecture, you will have a fully functioning Redux store, ready to be integrated into your application.

Setting Up Redux

To start using Redux, the first step is to install the Redux library. This can be done using npm as follows:

npm install redux

Once Redux is installed, we can import the createStore function and use it to create our store.

import { createStore } from 'redux';
import counter from './store';

const store = createStore(counter);

In this example, we import the createStore function and use it to create our Redux store, wrapping our counter reducer with it. This store is the central state manager that allows us to access and modify the state.

Understanding getState and dispatch

With the store in place, we now have access to three main methods that are part of Redux's core API: getState, dispatch, and subscribe. In this lecture, we'll focus on the first two.

  1. getState: This method returns the current state of the store. It helps us understand what the store contains at any given time.

  2. dispatch: The dispatch method is used to send actions to the store. Actions are plain JavaScript objects that describe what we want to do with the state—such as incrementing or decrementing a counter. By dispatching an action, we ask the reducer to update the state based on that action.

Here's an example:

// Dispatching actions to modify the state
store.dispatch({ type: 'STEP_UP' });
console.log(store.getState()); // Outputs: 1

store.dispatch({ type: 'STEP_DOWN' });
console.log(store.getState()); // Outputs: 0

When we dispatch an action, the store automatically invokes the reducer and passes it the current state and the action. The reducer then calculates the new state and returns it, allowing us to keep our application's state predictable and traceable.

The createStore Function

The createStore function is used to create the Redux store and requires a reducer as its argument. The store uses the reducer to know how to respond to different actions and update the state accordingly. When you call createStore(counter), Redux initializes the store with the reducer and sets the initial state based on the reducer's default value.

In our case, the counter reducer was previously defined like this:

function counter(state = 0, action) {
  switch (action.type) {
    case 'STEP_UP':
      return state + 1;
    case 'STEP_DOWN':
      return state - 1;
    default:
      return state;
  }
}

Testing Our Store

Testing is crucial when working with Redux, as it ensures that our reducers behave as expected. We can create a separate test file to validate the behavior of our store using Jest. Here's an example test that checks the default state and how the actions are processed:

import store from './store';
import { STEP_UP, STEP_DOWN } from './constants';

test('initial state is 0', () => {
  expect(store.getState()).toBe(0);
});

test('increments state by 1', () => {
  store.dispatch({ type: STEP_UP });
  expect(store.getState()).toBe(1);
});

test('decrements state by 1', () => {
  store.dispatch({ type: STEP_DOWN });
  expect(store.getState()).toBe(0);
});

These tests ensure that our actions (STEP_UP and STEP_DOWN) correctly modify the state. By dispatching actions and comparing the results against expected values, we can confidently verify that our reducers are working properly.

Conclusion

In this lecture, we incorporated Redux into our project by setting up a store using the createStore function, and we explored the key methods getState and dispatch to manage our application state. The store acts as a mediator between the reducer and the rest of our application, ensuring that state changes are predictable and traceable.

With this foundation, we are now ready to integrate Redux with our React components and start making our application truly dynamic. Stay tuned for the next lecture, where we will continue building upon this setup and begin rendering data from our Redux store within a React application.

Happy coding!

Video Transcript

00:00It's time for us to start using the Redux Library
00:03and we're gonna do that by creating our actual first store.
00:06We're gonna use the Get State and also the dispatch
00:09and let's just see it in action.
00:10Let's jump right into it
00:11and see the basics
00:13of actually using the Redux Library itself.
00:16Okay, before we continue, the next step that we need
00:18to do is we need to actually go ahead and install.
00:22And let me just uh, open up just one more window here.
00:26And the next step is that we need to do is we need
00:28to go ahead and also install our Redux.
00:31So to do that I'm gonna type NPM install.
00:34I wanna save it, so I'm gonna save it and Redux
00:39'cause it's gonna be for our production environment.
00:42Okay, let's go ahead and install it.
00:43And now that we have it installed,
00:45we could actually start using the built-in libraries
00:48that come within Redux.
00:50Alright, so let's go ahead
00:51and actually use Redux now that we have it installed.
00:55So I'm gonna go into my store itself
00:57and I'm just gonna go ahead on the top here and go ahead
01:00and import our uh, one function out of Redux,
01:04which will be Create Store.
01:07And we're gonna import it from Redux.
01:10Now that we have it imported, literally the only thing
01:12that we're gonna do inside of our store itself is wrap our
01:16counter with the Create store,
01:18which will then create our store.
01:20And as the store, any, even if it's imported multiple times,
01:24will only be created once.
01:26It's actually gonna create the store only once.
01:28We don't even have to create a variable.
01:31With that said, let's go ahead and save this.
01:32And it's literally all we had to do inside
01:35of our store itself.
01:36Now the store itself, which is being created,
01:39is creating a variable.
01:40And remember we were talking about that we did not have
01:43an actual store, we didn't have a place where that state
01:46and changes in our counter were actually being stored.
01:49And that's exactly what Create Store is doing now.
01:53Now that we have that, it actually is gonna create an object
01:56that has a few different methods, actually three methods.
01:59And we're gonna take a look at the first one right away
02:02and actually see the first two in this lecture.
02:05So I'm gonna go ahead into my store tests
02:07and first of all, my store tests right now
02:09should stop working.
02:11If I go ahead and test it out, we'll see
02:13that we have your two failures and that is
02:15because we never actually approach that counter anymore.
02:19It's not exported either, as you notice.
02:21And by the way, if we just wanna make things a little bit
02:23cleaner because we're exporting those items,
02:26let's just go ahead and place them with our exports there.
02:29So it'll be all combined, all the things
02:31that are being exported.
02:33Okay, I'm gonna go ahead and save
02:34and let's go into our test itself and update it.
02:37So I'm gonna start off by just commenting out everything
02:40inside of here and I'm gonna go ahead and create a new test.
02:43And what I wanna do is I want to test
02:45that my default value really equals zero.
02:48Now, to do that, I'm gonna go ahead
02:50and let me just check, uh, checking in IT values
02:54and for our check it in values, I'm gonna go ahead
02:56and create an arrow function. And notice
02:58This time around I'm not gonna open
03:00and close a curly bracket
03:01because I know I'm only gonna have one item in here.
03:05And because of that I'm just gonna go ahead
03:07and just call it within that line.
03:10To do that, what the test itself that I'm actually going
03:13to perform is going to, first of all,
03:15I'm gonna go call Expect and I'm gonna go ahead
03:18and open up that function and trigger that store.
03:23But this time around, instead of calling it as a function,
03:26it's actually an object now.
03:27And I'm gonna go ahead and get the state
03:29and the get state will literally just return
03:31to me the current state, the current value
03:33that is within the state itself.
03:35Next, I'm just gonna go ahead
03:37and I'm gonna check that it's two b equals two zero,
03:41which remains the same.
03:42Only this time around we're not approaching
03:44that function directly
03:45and we'll never approach them anymore directly.
03:48Now that we're using Redux, instead of that,
03:50we're always going to have it go through our mediator,
03:53which is our store itself.
03:55Firstly, we're gonna check for our state. Beautiful.
03:57So our state itself, if I go ahead
04:00and save this, go back into my terminal,
04:02we should see that our test passed.
04:04There are no, there are no issues.
04:06Let's go ahead and move on to our next test.
04:09Now, this time around, what we wanna do is we're not gonna
04:11actually call this function immediately inside.
04:14We're not gonna call that function at all.
04:16And instead of that, I'm gonna go ahead here
04:18and just place this in a separate line
04:20'cause we're gonna go ahead into our store itself
04:22and dispatch and we're gonna dispatch, we're not going
04:26to have a reference to the store anymore
04:29and that will be for our step up.
04:31And then again, I'm gonna get ahead a reference
04:33to the store itself immediately in the next line to check
04:36to see that the value really ended up
04:38to be the value we wanted it to be.
04:40Lemme go ahead and do this one more time,
04:43but this time around we're gonna be stepping down
04:48and we want the value to be zero.
04:51So there we go. Let's just save
04:53and check to see that we don't have any errors
04:55and we could see that everything is still running.
04:57And let's recap what we've done.
04:59So first of all, in our store itself,
05:01we've installed a Redux library.
05:03So first of all, Redux is now included
05:06into our dependencies.
05:08Once it's included to our dependencies, we're gonna pull out
05:11of Redux, just one function
05:13and we're gonna pull out the Create Store.
05:15Once we've done that, we're gonna wrap up our store
05:18with the Create store
05:19or literally, this isn't the store yet, this is a reducer.
05:22So we're gonna wrap up our reducer into,
05:25into the Create Store, creating that Create Store object.
05:30Now this happens only once, no matter
05:31how many times it's being imported, so we don't have
05:34to create here a variable,
05:35but if this is a little bit confusing to you,
05:37then you could go ahead and create a variable such
05:39as Cons Store
05:41and literally assign it the value that is here.
05:44Uh, but we're not gonna do that and then send that out
05:46because we don't need a reference currently
05:48to the store itself.
05:50Once we've done that in our testing itself,
05:53that's all we have to do inside of our store.
05:55In our testing itself,
05:57We've went ahead and created a one new test,
05:59which basically took our store and asked for it.
06:03Its current state, which is its initial state,
06:05and we wanted to make sure that it equals zero.
06:08Secondarily, we went ahead
06:10and also checked to see if Stepping Up works if when we step
06:13things from the in current state to one
06:17and we check to see it when it's from one to zero.
06:20In this case though, we didn't refer to the state
06:22or send the state instead of that,
06:24and this is how we do this in Redux, we actually call, uh,
06:28dispatch of uh, action.
06:30And we're basically saying, uh, please perform this action.
06:33Step up. Now I'm calling this action also recall,
06:36as we call these actions here,
06:37because this stepping up that actually happens, what happens
06:41behind the hood is this step, this,
06:43this dispatch meant will then go in our store
06:46and run through all the different
06:48reducers that are out there.
06:51In our case, we only have one and it's gonna go ahead
06:54and send that counter, that reducer,
06:56in this case it's called Counter,
06:57is gonna send it the current state if it exists.
07:00If it doesn't, it's just gonna, uh, fetch the zero value
07:03and then it's gonna send in the action itself.
07:05In this case our action here of type step up,
07:08we'll actually match the step up
07:09and that's why it will count our step up by one.
07:13And same applies for our down journey. And there we go.
07:17And that is how we create a very, very basic reducer.
07:22And with it, you could use this by the way,
07:23not only in React, but with any other, um, environment
07:26because reduce Redux is just incredibly wonderful.
07:30Now we're done with this very theoretical,
07:33very heavily theoretical chapter
07:35because in the next chapter we're gonna take this
07:37and actually integrate it into our React application
07:40and learn obviously a lot of other things related to Redux.
07:46In this lecture, we started using the Redux Library
07:49by actually creating our first store
07:51and seeing how things are connecting.
07:53In the next lecture, we'll move on
07:55to rendering our Redux data with the help of
07:59meeting the two together.

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!