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

Creating our First Reducer

Creating Our First Reducer: Introduction to Redux Basics

In this lecture, we take our first steps into Redux by creating a simple reducer. This initial implementation won't be fully backed yet, but it will provide a solid foundation for understanding the basic concepts behind reducers and how they fit into the Redux architecture. Reducers are a core part of how Redux operates, helping us manage and transform state in a predictable way.

What is a Reducer?

In Redux, a reducer is a function that takes the current state and an action as arguments and returns a new state. The concept is derived from the idea of reducing multiple inputs into a single output. Reducers are pure functions—they don't modify the existing state directly; instead, they return a new version of the state based on the given action. This makes it easier to manage and predict state changes, which is a key principle of Redux.

Reducers are inspired by Flux, a unidirectional data flow pattern, and were designed by Dan Abramov as a way to simplify state management and make data changes more predictable and traceable.

Setting Up the Redux Store

To start building our first reducer, we need to set up a Redux environment. In this lecture, we create a file named store.js, where we will define our Redux store and the first reducer for our application—a simple counter. This counter reducer will serve as an introductory example to help us understand the basic concepts.

Here's how we define the counter reducer:

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

Breaking Down the Key Elements

  1. Reducer Function: The counter function takes in the current state and an action. The state is initialized to 0 if it isn't provided.
  2. Action Types: We use a switch statement to determine the type of action and update the state accordingly. If the action type is 'STEP_UP', the state is incremented by 1. If the action type is 'STEP_DOWN', the state is decremented by 1.
  3. Default Case: If the action type does not match any of the specified cases, the current state is returned without any changes. This ensures the reducer always returns a valid state.

What are Actions?

In Redux, actions are plain JavaScript objects that describe what happened in the application. They must have a type property, which is a string that tells the reducer how to change the state. The type property is often defined as a constant to avoid typos and make the code more maintainable.

For our counter example, we define two action types:

const STEP_UP = 'STEP_UP';
const STEP_DOWN = 'STEP_DOWN';

These constants are used to dispatch actions to the reducer, ensuring that our application state updates correctly.

Connecting the Reducer to the Store

To manage the state with Redux, we need to create a store using the createStore() function from Redux. The store is a centralized state container that allows us to access the current state, dispatch actions, and subscribe to changes.

Here is how we create the store and use the counter reducer:

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

const store = createStore(counter);

Testing the Reducer

Once the store is created, we can test our reducer by dispatching actions and observing the changes in state:

store.dispatch({ type: 'STEP_UP' });
console.log(store.getState()); // 1

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

Every time we dispatch an action, the store calls the reducer with the current state and the action, and then the reducer returns a new state based on the action type.

Understanding Pure Functions and State Immutability

One of the reasons Redux is powerful is that it enforces state immutability. Reducers are pure functions; they don't modify the existing state object but instead return a new state. This ensures that the state changes are predictable and easy to debug. Pure functions also make it easier to implement features like time-travel debugging (which allows you to move back and forth between state changes).

Why Use Reducers?

  • Predictable State Updates: By always returning a new state instead of modifying the existing one, reducers make state changes predictable and easy to trace.
  • Pure Functions: Since reducers are pure functions, they provide better reliability and ease of testing.
  • Centralized State Management: When managing complex applications, having a central point for state changes helps in keeping the state consistent across the entire application.

Conclusion

In this lecture, we explored the foundational concept of reducers in Redux and created our first simple reducer. This is an important milestone, as reducers are at the core of how Redux manages state. By understanding how to define a reducer and how actions interact with the state, you have taken the first step towards mastering more complex state management with Redux.

In the next lecture, we will build on this foundation by connecting our reducer to our React components and expanding the capabilities of our Redux setup.

Happy coding!

Video Transcript

00:02It's time for us to create a reducer.
00:04And to do that we're going to use Redux, which
00:07by the way is kind of like the name behind re uh, Redux.
00:10It's the idea of reducing things into a state,
00:14which is an incredibly powerful
00:15and incredibly beautiful concept that, uh, was created
00:19by Dan Abramov and inspired by Flux.
00:22And through the through it we're gonna understand the basic
00:24concept of how do we create these.
00:27We're gonna start with one reducer
00:28and throughout the lectures
00:30and throughout the chapters, we're gonna create more
00:31and more complex reducers.
00:33But let's jump right into it and let's see
00:34what a reducer actually is.
00:38Okay? It's time for us
00:39to start addressing the elephant in the
00:42room, which is Redux.
00:43Now even before we use the library, I wanna walk you
00:46through the basic concepts behind it
00:48so you really understand how to use it and also why
00:51and where would you want to use Redux over any other ver
00:55other way to deal with your data if it's flux
00:58or even if it's natively in a component
01:00that self-manages itself with the state
01:03as we've done previously.
01:05Okay, so let's go into our application
01:07and I'm gonna go ahead
01:08and literally start creating our redux environment.
01:12And to do that, I'm gonna go ahead and create a new file
01:15and I'm gonna call it store js.
01:17I'm gonna go ahead and save it and let's go ahead
01:20and start building out our store.
01:22And I'm gonna start up from our basic concept that we've had
01:25inside of our application, which was a counter.
01:28So I'm gonna go ahead and literally just create a
01:30new function called Counter.
01:33Now our counter itself is gonna accept two
01:35different parameters.
01:37The first parameter is gonna be the current state
01:39that it's in, and the second parameter will be the action
01:43that is being opposed to it, that is being committed
01:46to it at this point in time.
01:48Now the action itself
01:50and the state itself need a default state.
01:53So I'm gonna go ahead and define the beginning state
01:56to be zero, just like we did when we were working inside
02:00of our component itself inside of our counter.
02:03And we set our counter to be zero.
02:06So inside of my store, I'm literally creating a counter
02:08and setting a beginning state for our counter itself
02:12to be in position zero.
02:14The next step that I'm gonna do is I'm gonna go ahead
02:17and I'm gonna switch here.
02:18I'm gonna create a switch case.
02:20And in the switch switch case,
02:22I'm gonna list out all the different types of actions
02:24that could be provided.
02:26Now actions are sent with a type parameter.
02:29So not dot, yeah, dot.is okay.
02:32Um, and by the way, if I wanted to,
02:33I could have deconstruct my action
02:35and literally just grab the type itself from it directly,
02:38but in this case and just type your type
02:40and then I could just use your type.
02:42But in this case, I'm not gonna do that
02:44'cause I might have other parameters being sent
02:46with the action itself that need to be used
02:48and I don't wanna list them all out.
02:51And os I want to be able
02:52to call another function down the line if I choose to do so.
02:55Now I'm gonna go ahead
02:57and list out the different types of actions
02:59And I'm just literally gonna create a cons a, a constant
03:02and I'm gonna call it step up
03:06and just set it a value that will be unique.
03:08So it's gonna be step up and let's go ahead
03:11and create another constant.
03:13And this constant is going to be a step down.
03:15And by the way, I didn't have to use consonants,
03:18but I personally prefer using them,
03:20especially if there might be a scenario where we need
03:22to type the same copy in different places to avoid typos.
03:26Um, and just to make things more descriptive
03:29and more clear about what could be done.
03:32Okay, so in my switch itself, I'm gonna go ahead,
03:34I'm gonna start creating those cases.
03:36In the case of step up, I'm gonna do one thing.
03:40In the case of step down, I'm gonna do another.
03:43And last but not least, we also will always want
03:46to have a default state.
03:47And that is because anytime we call the counter,
03:49even if nothing is happening,
03:51we wanna return the current state.
03:53So literally in the default state, I'm just gonna go ahead
03:56and return the state as it is without changing it,
03:59without modifying it.
04:01On the contrary, whenever I'm using a step up,
04:04I'm gonna go ahead and because we're using a primitive value
04:06here, we don't have to worry yet about overriding values,
04:10but we're gonna talk about that in the next chapter.
04:13But for now, let's go ahead and return our state plus one
04:16because that is gonna be the next step after that action.
04:20And for our step down,
04:21we're gonna return our state minus one.
04:24Notice how I'm not assigning the value
04:26and to state, I'm literally sending in a new state,
04:29a new variable that will have those values to combine.
04:32And we're gonna take a deeper look into why we're doing
04:35that, uh, in a later lecture.
04:38But literally what we, all we've done here is
04:40created a function.
04:41We had to set up a initial state to it,
04:44if it's being called without any value
04:46and we set an action which would define the action
04:49that actions that could be done.
04:52If I literally just go ahead here and I do a console log
04:56and I want to test this out just for a second,
04:58I'm gonna call our counter.
05:00I'm gonna send your uh, state of zero supposedly,
05:04and I'm gonna go ahead and set your A type
05:06and set that type to be step up.
05:09Now if I go ahead and run this
05:11and if I don't have any error there,
05:12first of all, nothing will happen.
05:13So I'm gonna go into my app itself
05:16and let me just import the store.
05:19And for now the store literally is empty
05:22and is not exporting anything.
05:23But I'm gonna go ahead and import store from store
05:27and lemme go ahead and save this
05:28and see if I'm getting an error here.
05:30Um, I might, so I have your problem
05:32because store is not defined,
05:34but let's ignore that for a minute
05:36'cause you're gonna see that we're getting that value.
05:38One is and is exactly the value
05:40that we would expect it to send us.
05:42So we see here in our store itself,
05:44our counter is growing up by one.
05:47In this lecture we were introduced
05:49to the concept of reducers.
05:50And in the next one we'll go ahead
05:52and actually test out our first Reduce Reducer.
05:55Reducer using just.

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!