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

The Power of Redux and Arrays

Managing State with Redux and Arrays

In this tutorial, we'll explore one of the most powerful aspects of Redux: its ability to manage application state using arrays. By the end of this tutorial, you will understand how to take advantage of Redux to handle multiple components, extract data for better state management, and use JavaScript's ES6 tools to maintain clean and reusable code.

Introduction to Redux and Arrays

Redux is a state management library that provides a single, predictable state container for your application. One of the strengths of Redux is its capacity to extract and centralize all application data, making your components much simpler and easier to test. In this tutorial, we will leverage arrays to create multiple counters and understand how to control and manipulate data in Redux.

Key Takeaways:

  • Use Redux to manage multiple counters.
  • Leverage ES6 tools like the reduce function to manipulate data.
  • Utilize Redux to maintain clean separation between your UI and data.

Step 1: Extracting Data into Redux State

The first step in creating multiple counters is to ensure that our data is not trapped inside individual components. Instead, we use Redux to extract all state data and store it in a centralized container, making it easier to create and manage multiple components using the same data.

For example, instead of having each counter component manage its own state, we store the entire array of counters in Redux. This allows us to:

  • Share data between multiple counters easily.
  • Extract the state out of individual components and keep the logic centralized.

Here's how a typical state structure may look:

const initialState = {
  counters: [0, 0, 0] // Array to store multiple counters.
};

By moving all the counters into an array stored in Redux, each component can access its own counter value without managing the data locally.

Step 2: Implementing the Reduce Function

In Redux, the reduce function is a powerful tool introduced in ES6 that enables us to summarize or aggregate the values of an array. In our counters example, it can be used to calculate a total count from all the individual counters.

To use the reduce function, you can define a reducer that accumulates values in your array, like this:

const total = state.counters.reduce((sum, currentValue) => sum + currentValue, 0);

In this example, reduce iterates over every value in the counters array and calculates the total count. This is helpful for scenarios where you need a summary or aggregated value, for example, to display the total number of counts across all counters in your UI.

The reduce function is not limited to summing counters. You can use it to apply a wide range of logic to array values, such as finding the average or filtering specific values.

Step 3: Updating State and Passing Data to Components

The next step is to connect the Redux store to our components. By using mapStateToProps, we can pass specific parts of the Redux state to each counter component.

Here is how you connect a counter component to the Redux store using mapStateToProps:

const mapStateToProps = (state, ownProps) => {
  return {
    count: state.counters[ownProps.index]
  };
};

The count prop now holds the specific counter value from the counters array based on its index. This connection allows each counter component to have its own unique data from Redux while still sharing the same overall state.

To dispatch actions that modify specific counters, you can use mapDispatchToProps:

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onIncrement: () => dispatch({ type: 'INCREMENT', index: ownProps.index }),
    onDecrement: () => dispatch({ type: 'DECREMENT', index: ownProps.index })
  };
};

This ensures that each counter's action only affects its own data in the state.

Step 4: The Power of Separation

One of the biggest advantages of Redux is its ability to separate your application's data from its UI. By storing all data in Redux, components become simpler and less dependent on each other. This means:

  • Reusability: You can reuse the same counter component in different places because it no longer has its own state.
  • Scalability: Adding more counters is easy since they all rely on a shared state in Redux.
  • Control: Centralized data in Redux provides a clearer picture of the state, making it easier to understand the application's current status.

Example of Component with Total Count

Suppose you want to display the total count of all the counters in your UI. With the extracted data stored in Redux, this becomes straightforward:

const TotalCounters = ({ counters }) => {
  const total = counters.reduce((sum, currentValue) => sum + currentValue, 0);
  return (
    <div>Total Count: {total}</div>
  );
};

const mapStateToProps = (state) => ({ counters: state.counters });
export default connect(mapStateToProps)(TotalCounters);

By using the reduce function, we can easily create a TotalCounters component that displays the total value of all counters. This highlights the power of centralized state management, where multiple components can share, aggregate, and manipulate data without being directly dependent on each other.

Conclusion

Managing state with Redux is a great way to extract data out of individual components, centralize your application state, and make your code more predictable and reusable. In this tutorial, we:

  1. Learned the benefits of moving data into Redux.
  2. Leveraged the reduce function for data aggregation.
  3. Connected Redux state to individual components while keeping the logic centralized.

These techniques are essential for building scalable and maintainable React applications with Redux. Centralizing state in Redux and using tools like reduce and Object.freeze can significantly enhance the development process, providing both flexibility and control over application data.

Video Transcript

00:01Absolutely one of my favorite features in Redux.
00:04By extracting all our data into an external element,
00:07turning our, our, our components literally
00:10to just be buckets of data, it makes it so much easier
00:13for us to then use all these different features
00:15and reuse data.
00:17So we're gonna use the reduce function than which was
00:19introduced in ES six to array.
00:21But really the main point of this lecture is about the power
00:24of data augmentation, where you have complete control
00:27of your data and you could decide
00:29where your data is gonna go instead
00:31of having your data trapped inside of a specific component.
00:35Now, another powerful element of having all
00:39of our data extracted out be beyond the fact
00:42that now we could create multiple components very easily is
00:46and, and share between this data externally.
00:49Where does this come useful?
00:50So in a very common scenario, you'll have where you need
00:53to do something with that data beyond only
00:56inside of the app itself.
00:58Let's say for example, we wanted inside
01:00of a bracket right here to position our total amount of, uh,
01:04values that are inside of our counter.
01:06It's a very theoretical example here.
01:09Now what I would do is literally,
01:11I'm just gonna go into my props itself
01:12and uh, well I already have the data itself,
01:15so lemme just create here another variable
01:17and I'll just call it total.
01:19And our total, I'm gonna use a ES six function of arrays,
01:23which is called reduce.
01:25Now, the reduce function literally goes through item
01:28by item sending in our, uh, current value
01:33that has been combined together
01:35and the current value that we're in.
01:36Now, in my case of what I really wanna do is a summary.
01:39So what I'm gonna do is I'm always gonna connect them
01:41together, but I could have made it a duplication.
01:43I could have done really what I wanted with it,
01:45and I wanna start from zero.
01:47So it's two parameters. The first parameter,
01:49the first parameter is a function.
01:53In this case, we created an arrow function
01:55that literally just combines it.
01:57Sentence two values, the, the total so far
01:59or the last value in
02:01and the current value within our index.
02:05And what I'm literally doing is I'm starting from zero.
02:07So first time around zero comes in
02:09and eight, each time that I'm counting it,
02:11I'm just gonna add whatever is inside of the current value.
02:14So if I go ahead and save this, add my semicolon,
02:18and then go ahead and put that total inside of here
02:21and save it again and go into our browser, you'll see
02:25that now whenever I'm gonna add to my counter,
02:27the counter internal counter would grow.
02:30But also whenever I'm gonna add in the items below
02:33or reduce for that matter, then our counters totals will
02:38reduce as well.
02:39And there you go. And you see a very, very nice example of
02:42how something like this in built in React.
02:45If we would had all of our data within each of our counters,
02:50it would be incredibly complicated.
02:51For one, we would have to extract the data out.
02:54And what would happen naturally is
02:56as you're building a counter,
02:57you would do it all internally, but
02:58Then suddenly you'll realize that, for example,
03:01with the Facebook story, where they had a counter
03:04for their chats
03:05and they needed now to share
03:06that information in different places,
03:08and they were getting outta sync
03:09because their specific components
03:12were managing the data itself.
03:14And that's kind of like where oto, the,
03:15the React philosophy came in and then flux and uh,
03:19and now reduce, which reduces probably the best solution
03:22so far regarding keeping your data.
03:25So once our data is stored externally,
03:27we could manipulate it and control it a lot easier.
03:30Now there's a lot more that we want to do with data
03:32and among it to make sure that we're not so deeply
03:35tying our React application.
03:37With Reduce, we kind of wanna make our react layer
03:42unaware from where it's getting its data.
03:44Currently, it's completely aware,
03:46it knows it's coming from the store.
03:47And one of the next steps that we really wanna do is we want
03:50to extract out these steps
03:51so we could then control them and swap them.
03:54Even if for example, in the future we decide
03:56that we're not using Redux anymore,
03:58then we can easily change it without even going into our,
04:02uh, visual layer at all,
04:03which would be the perfect solution.
04:05And right now we're getting closer to that perfect solution,
04:08but with it, we wrap up this chapter with a solution
04:11that is working that you could start
04:12using already tomorrow morning.
04:14But it's not the ideal setting
04:15when you're setting your data.
04:17'cause right now we have this two problems,
04:19really two main problems.
04:20And one is that our, there is a very big flow of data.
04:25So although our application is relatively small
04:27where we only have our app and our counter,
04:30but in reality what's actually going on is
04:32that we're having here a lot
04:33of data passing from file to file.
04:35And it's very visually.
04:37So, so if you end up, uh, not sending something,
04:39it could get very confusing that one, as your project grows,
04:43that's one problem you're gonna try to address.
04:45And the second problem that we're gonna try
04:46to address is the problem that we're talking right now about
04:49this tie in of all this data
04:51where we really don't need all this data inside of our app.
04:54We need to figure out a way, how could we get our
04:57components themselves to be completely unaware to
05:00how the content is coming in, which is our ideal scenario.
05:04So we'll see you in the next chapter.
05:06We'll reach, start addressing those
05:07problems in this lecture.
05:09I hope you really saw the full circle of why it's so amazing
05:13to have your data separated from your visual
05:16layer in the next lecture.
05:18We're gonna continue making our content more dynamic now
05:21that our data isn't an external layer,
05:23making it a lot easier for us
05:24to just do whatever we want on the visual layer.

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!