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

Managing Complex Data Types in Redux Reducers

Managing Complex Data Types in Redux Reducers

In this tutorial, we will explore how to manage complex data types in Redux reducers. This includes working with arrays, understanding the importance of immutability, and learning why reducers should never modify the state directly. By the end of this tutorial, you will understand how to create effective reducers that maintain predictable state management in your application.

Introduction to Reducers and State Management

Reducers are pure functions in Redux that specify how the application's state should change in response to an action. A key principle of reducers is that they must not modify the existing state directly. Instead, they should create a copy of the state and return the updated version. This helps maintain immutability, which ensures that previous states remain unchanged and predictable.

In this tutorial, we will:

  1. Convert a state variable from a primitive type to an array.
  2. Learn why direct state modification is problematic.
  3. Discover how to ensure immutability while working with arrays.

Step 1: Moving to Complex Data Types

In our example, we initially have a simple counter state represented as a number. Our goal is to expand this into a more complex data type — specifically, an array of counters.

Changing the State Structure

We start by changing the state in our reducer from a single number to an array. This allows us to manage multiple counters at once.

const initialState = {
    counters: []
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT':
            // We will explore this in detail later.
            return state;
        default:
            return state;
    }
};

Avoiding Direct State Modification

A common mistake when managing arrays in reducers is modifying the state directly. For instance, using push() to add an item to the array directly changes the original state. In Redux, we must avoid this to prevent unexpected behavior.

Example of incorrect state modification:

case 'INCREMENT':
    state.counters.push(1);  // This directly modifies the state.
    return state;

Direct modification can lead to various issues:

  1. Unpredictable Behavior: The state may change intermittently, leading to bugs that are difficult to trace.
  2. Loss of Version Control: Redux relies on each change being a new version of the state. Direct modification bypasses this mechanism, making debugging and tracking changes more difficult.

Step 2: Ensuring Immutability with Arrays

Instead of modifying the state directly, we must create a copy of the array and return the updated state.

Correct Approach to Update State

To add an item to our counters array without modifying the original state, we can use the spread operator to create a new array:

case 'INCREMENT':
    return {
        ...state,
        counters: [...state.counters, 1]
    };

In this example, we are creating a new array by spreading the existing counters array and adding the new value (1). This ensures that the original state remains unchanged, and we return a new state object.

Step 3: Testing for Immutability

To verify that our reducer maintains immutability, we can use JavaScript's Object.freeze() method during testing. Object.freeze() prevents modifications to an object, allowing us to confirm that our reducer does not alter the original state.

Using Object.freeze() in Tests

import { createStore } from 'redux';

const store = createStore(reducer);

// Freeze the state to prevent modifications
Object.freeze(store.getState());

// Dispatch an action
store.dispatch({ type: 'INCREMENT' });

// If the reducer tries to modify the state directly, an error will be thrown.

This testing technique helps ensure that reducers follow Redux's best practices by not modifying the original state.

Step 4: Handling Arrays in Reducers

When working with arrays in reducers, it is important to remember that arrays are reference types in JavaScript. Comparing arrays directly can lead to issues, as two arrays with the same content are not considered strictly equal (===). Instead, when working with arrays, use methods like .every() to compare contents or leverage deep equality checks.

For example, when writing tests to compare array values:

const state = reducer(initialState, { type: 'INCREMENT' });
expect(state.counters).toEqual([1]);  // Use toEqual for deep comparison

Conclusion

In this tutorial, we covered how to manage complex data types, specifically arrays, in Redux reducers. We emphasized the importance of immutability and avoiding direct state modification, which is crucial for maintaining predictable and bug-free applications. By using tools like the spread operator and Object.freeze(), we can ensure that our reducers behave correctly and keep our application's state consistent.

Next, we will dive into more advanced topics, such as optimizing reducers for performance and handling nested structures within the Redux store. Stay tuned and keep experimenting with these concepts to solidify your understanding of Redux state management!

Video Transcript

00:02Now that we're moving into complex data types,
00:04in our case arrays, we need to think about a few things
00:07that we didn't have to think previously.
00:09We're gonna take a look at a few new ES six features
00:12as well in the process.
00:13But our main get out of this that I want you to get is
00:16that reducers should never change the state.
00:19They should make always duplications.
00:20And we're going to really understand that
00:22by the end of this lecture.
00:24So what we wanna do next is we wanna
00:26basically separate them.
00:27And to do that, I'm gonna take a step back for a second
00:30and talk about another feature, another element of reduc.
00:34So you need to be mindful of that is not done
00:37for you automatically.
00:40So to do that, I'm gonna go ahead into our store
00:42and let's go ahead and change our counter
00:44to counters in a plural.
00:46And instead of having a state that is a number,
00:49I'll set it up as an array.
00:51Now, just for the sake of our presentation here, right now,
00:55I'm gonna go ahead to the state and push into a data.
00:58This is absolutely not true.
00:59This is not what we're actually gonna do.
01:01Um, well state push one
01:04and let's do for the step down a push downwards.
01:07Now, obviously, I don't know if it's obviously,
01:10but you don't want to do this.
01:12You, you could by mistake do this often.
01:14And what don't you wanna do is you never want
01:17to modify your state.
01:18And what we're doing right here is we're directly
01:21modifying our state.
01:22Now, it creates a few problems.
01:25One is that our state will change
01:27before it actually completed to change.
01:30That is if we have a lot of data
01:32and we're making a change directly to our state,
01:35our state is gonna modify intermittently
01:38before it's completely modified, which could create very,
01:42very weird bugs.
01:44Beyond that oto, we're gonna kill the possibility
01:46of us having aversion control of some system
01:49because now we're overriding the mechanism
01:52that the store itself is in charge of.
01:54The only thing that should be modifying our store is the
01:57create store, which is happening behind the hood.
01:59So when we're actually changing it ourselves inside
02:02of our actions, inside of our reducers more accurately, then
02:06what we're actually doing is we're actually modifying
02:10and doing a job that we're not supposed to do.
02:12But imagine that you did that by a mistake.
02:14How could you track it down?
02:16So firstly, if we go into our testing now,
02:18obviously this whole thing won't be true anymore.
02:20For one, we can't use to be anymore.
02:23Instead of to be, we need to set it to be, uh, to not to be,
02:28because instead of to B, we want to use something else
02:32to B is used to compare a strict comparison
02:35where I'm gonna say if equals zero equals zero,
02:39but when we're working with arrays, uh,
02:41one array will never be strictly equal.
02:44Another array.
02:45In other words, if I took you
02:46or this gets state, which equals an empty array,
02:49and lemme just go ahead and kind of like get rid
02:52of all the rest here and save this.
02:54Our state does equal an array and it is an empty array,
02:58but it's not a, to be, it is not an absolute equality.
03:01And thus, if we looked into our testing, we'll see
03:04that now we have a failure in our test.
03:06We have two failures.
03:07So first of all, our counter is not defined.
03:10That is true enough
03:11because there is no counter, there are counters in a plural,
03:15um, which is something that we could update inside
03:18of our code, but we're not gonna do that yet.
03:20And secondarily, if we find our next error inside of our,
03:24uh, store test, uh, counter not define,
03:27oh well we're, are we using counter?
03:29Where are we using counter here? Counter, counter.
03:33Maybe it's in the store itself. Oh, here we go.
03:36In the store itself, we want to use counters.
03:39Let's go ahead and see this.
03:40So really the error that I was looking here is comparing
03:44with two values that are the same
03:49but are not equally the same.
03:50So I'm getting here, uh, uh, uh, values
03:53that are coming back in defined coming back,
03:55not the way we want them to come back.
03:58So the next step of what I want to do is I want
04:00to basically make not a direct comparison of A to B,
04:04but instead of using A to B I'm going to use two equal.
04:08So I'll use a two equal, which two equal is gonna compare
04:12between the two values,
04:13but it's not gonna be an explicit comparison,
04:16but it's actually gonna check to see that the values
04:18that are coming back between the two are the same.
04:20So if I take a peek at this,
04:22I'm not gonna get an error anymore.
04:24Let's go ahead and continue running our two other
04:26tests to do that again.
04:28What I'm gonna do is I'm gonna check
04:30to see if our state equals
04:32to one when we're first pushing it.
04:34'cause the first time around it's gonna be adding one.
04:37Let's put your minus oso. So there's a difference.
04:40Excuse me. And for our second value here,
04:44we'll have your the first value as one
04:46and the second value as minus one.
04:47And if we check this out again in our test, we'll see
04:50that our tests are going to not, oh,
04:53we don't wanna be do two B anymore,
04:55but we wanna make sure that we're setting here a
04:57two equal as well.
04:59And if we take a peek at it, we'll see
05:01that now our tests will pass.
05:03Okay, so now that we got that basic premise, we got our code
05:07to go through our testing,
05:09but technically speaking this is completely illegal.
05:12We should not be pushing our state directly.
05:15But now that our comparison is actually accurate,
05:18we are comparing between the values
05:20and not the explicit object.
05:22What I wanna do next is also make sure
05:24that I'm actually not overriding the same object.
05:28So inside of our test itself, what inside
05:30of our test itself, what I'm gonna do is I'm gonna go ahead
05:33and I'm gonna, as soon as our, our test begins,
05:36and soon as we're trying to modify it,
05:38I'm literally just gonna call our
05:40constant, uh, new constant.
05:42I'm gonna call this state and I'm gonna take our store
05:45itself as it is.
05:49Now, I'm gonna go ahead and do this even
05:51before we dispatch a change.
05:53'cause we wanna make a modification to this object
05:56before we actually do anything to it, okay?
06:01And what I'm gonna do is I'm gonna call the the ES six
06:04object freeze.
06:07Now, object freeze accepts an RA or an object.
06:10And what it does, it makes sure that that's specific object,
06:15excuse me, that specific object is frozen
06:19and cannot be changed.
06:21Once I've done that, if I go ahead and I go back
06:24and continue with this expect mechanism,
06:27then we should be getting a failure
06:28because for one, oh for one, uh, if I go ahead
06:33and do that, if I just run my code again, we'll see that.
06:36Now in my terminal itself, when I'm running it,
06:38I'm gonna see, uh, cannot add property.
06:41Zero object is not extensible.
06:43And what's nice about this, this is only
06:44happening in our test suite.
06:46So we could test things out to make sure
06:48that everything is working appropriately without actually
06:50adding it into our live environment as well.
06:54Okay, so let's go ahead
06:55and implement this oto in our next element.
06:57So I'm just gonna go ahead here and grab that
07:01and put it right in here.
07:04And next is, I'm gonna go ahead
07:06and make sure that I'm gonna expect our
07:11date to be frozen.
07:13Oh, you know what? E even when I froze the state,
07:16I actually don't wanna send that.
07:17I actually wanna send a new state again
07:19because the state has changed
07:21by the time we made that dispatch meant.
07:23So I'm gonna go ahead here and just set here the get state.
07:26Um, so this will remain the same.
07:27All I'm doing is getting a reference
07:29to the current state and freezing it.
07:32Okay, so let's go ahead and save this.
07:34And this will make sure that every time we're making a
07:36modification, we're first freezing our object
07:39before we're making that modification.
07:41So we should expect now to get two errors
07:43or it doesn't really matter if we're only seeing one
07:45of them, uh,
07:46or we're getting a few errors here,
07:48two fails, which is beautiful.
07:49We're ignoring the top. We're fine with that.
07:50For now, we're only focused on our store test itself.
07:54In the next lecture, what I'm gonna do,
07:55and let's just walk through this again
07:57before we wrap things up for this lecture
07:59for now, I did the wrong thing.
08:01I converted our reducer into an array
08:03that I could do very easily, no problem.
08:06But I'm not allowed to actually change our items
08:09directly instead of at changing our items directly.
08:12What I need to do is not change them directly.
08:15So instead of changing them directly, let's go ahead
08:17and just implement how do we actually make them not return
08:22what they're not supposed to return.
08:24So I'm just gonna go ahead here
08:26and for my state itself,
08:27what I'm gonna do is I'm gonna go ahead
08:29and into, by the way, and this is
08:32complete a complete fallacy
08:33because we have your, uh,
08:35supposedly a change in our counters, which is not true.
08:39What we're gonna do, let's do this in the next lecture.
08:41And let's say that we're gonna have three counters just
08:44to mimic the three counters that re we already have
08:47as the default state,
08:48and then deal with the changes that we're gonna have to do.
08:52And as we do, those changes also address the fact that
08:54We're never allowed to actually change them
08:57directly in this lecture.
09:00We really took us to a new path for our reducers now
09:03that they could store arrays,
09:05but with it, we also brought up a warning
09:07that we really don't want our reducers
09:09to manipulate our state directly.
09:12In the next lecture, we're gonna take a look at
09:14how do we address those issues by creating multiple counters
09:19and, and, and with those multiple counters,
09:21how do we avoid those duplications?
09:24I.

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!