02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous Video
Chapter is concluded.Next is

React Redux Connect Method Explained

Using the React-Redux connect Method for State Management

In this tutorial, we're diving into using the connect method from React-Redux, a better way to manage state rather than using React's native context directly. Dan Abramov, the creator of Redux, highly recommends using this method because it helps solve many problems while avoiding the fragility of React context.

Let’s see how we can implement the connect method to connect components to our Redux store without directly managing the context.

Step 1: Understanding the Problem with Context

In the previous lecture, we discussed that using context is generally not a good idea for state management, especially for larger applications. While the React Context API provides a way to pass data deeply through a component tree, it can be fragile and isn't recommended for use in real-world applications, as per the official React documentation.

Instead, we want to use the React-Redux library’s connect function to create a more stable and scalable state management solution.

Step 2: Setting Up the Provider

In the previous setup, we wrapped our entire application with a Provider component. This Provider component helps us share our Redux store with every component in our app without manually passing props from component to component.

import { Provider } from 'react-redux';
import store from './store';

<Provider store={store}>
  <App />
</Provider>

Step 3: Introducing the connect Function

The connect function allows us to bind our Redux state and actions directly to our components. This prevents us from needing to work directly with the fragile context API.

Here's how to implement it:

Example Component: Button

Let’s create a Button component that interacts with the Redux store using connect. We’ll use the connect function to bind a click action and access the current state.

import React from 'react';
import { connect } from 'react-redux';
import { addCounterAction } from './actions';

const Button = ({ onClick, counters }) => {
  return (
    <button onClick={onClick}>
      Add Counter (Current Count: {counters.length})
    </button>
  );
};

Step 4: Mapping State and Dispatch to Props

We need to use two functions—mapStateToProps and mapDispatchToProps—to connect the component to the Redux store.

  • mapStateToProps: Extracts the state that we want to pass as props to our component.
  • mapDispatchToProps: Creates the dispatchable actions that we want to pass as props.
const mapStateToProps = (state) => {
  return {
    counters: state.counters,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onClick: () => dispatch(addCounterAction()),
  };
};

Step 5: Connecting the Component

Finally, we use the connect function to link the state and dispatch to our Button component.

export default connect(mapStateToProps, mapDispatchToProps)(Button);

Summary of Changes

  1. Created the Button Component: We created a simple button component that accepts two props—onClick for adding counters and counters for displaying the count.
  2. Implemented mapStateToProps: This function maps the counters from the Redux state to the Button component’s props.
  3. Implemented mapDispatchToProps: This function binds the addCounterAction to the onClick prop.
  4. Connected Everything: Finally, we used connect to combine everything and export the updated Button component.

Conclusion

In this tutorial, we learned why using React context directly for state management is often not recommended. Instead, we used the connect method from React-Redux to manage our application's state more reliably.

By wrapping our app with a Provider, and using connect to bind state and actions, we have a scalable way to manage state in our components.

If you enjoyed this tutorial or have any questions, feel free to reach out or leave a comment. Happy coding!

Video Transcript

00:00As we said in the previous lecture,
00:01using the context is probably not a great idea.
00:04And Dan Abramov, the creator of Redux
00:08and React Redux Library really suggests to use this method.
00:12So we're gonna talk about how to the,
00:14in the using React Redux is connect method,
00:17we could actually create
00:18and solve that problem without approaching our
00:21context directly.
00:22So let's see at that solution with it,
00:24that is our last lecture in this title.
00:28In the last lecture, we set up our provider
00:32and our provider was then providing our information
00:34currently for the app.
00:35But it could be for any item, any component
00:38where we set to it a context.
00:40But as we said, the context itself is very fragile.
00:43And as the official React documentation say,
00:46please don't use it unless you really have to.
00:49So with that said, we wanna depend on a library.
00:51In our case, we wanna depend on React Reduc
00:55to solve our problem, to avoid the need
00:58to use our context directly.
01:01To do that, I wanna showcase how would you do
01:03that using one component.
01:04And I'm gonna focus on this button component.
01:06And what I wanna do is I'm gonna go ahead
01:08and extract it out into its own variable.
01:11And I'm gonna use a, because it's such,
01:14such a simple component,
01:15I don't even need a rendering method.
01:17All I'm gonna do is I'm gonna create a new
01:19constant, which is called Button.
01:21And I'm literally just gonna go ahead
01:23and wrap it in a self enclosed function.
01:27And literally I'm just gonna go ahead and create a button.
01:34What am I doing? Beautiful. So I've just created a button.
01:39The next step in my process, now
01:41that I've created a basic button is I actually am going
01:44to need to have a few properties in it, right?
01:46The first one is gonna be our on click.
01:48And our second, let's assume
01:50that we need something from the store as well,
01:52because I wanna showcase the concept of how to work with it.
01:56Okay? So let's assume that we decided
01:58that we want our button to have here an add feature.
02:02And beyond that we also wanted
02:03to maybe showcase our counters and their length.
02:07So we wanna make sure, and we wanna send
02:09that into our button.
02:10Secondarily, we wanna make sure that on click,
02:13we're actually gonna call our on click.
02:15And in our case, our on click was,
02:18let's just call it on click.
02:20Alright? So we want to, we're gonna be sending an on click
02:23and we're gonna be sending a calendar.
02:25So let's go ahead and let's implement it.
02:27So the next step is when we're working in the,
02:31in the context of Connect,
02:33and that's what, uh, react, redo Redux calls it.
02:37So let's go ahead and import that.
02:38I'm gonna import connect, well, it's actually not a default.
02:43So connect from React Redux.
02:48Now notice how we're still tying
02:49with React even though we're supposedly separating.
02:52So the solution that I
02:54provided of putting your actions in here
02:55and having your deep connection only there
02:58to me seems like a good solution.
03:00But as your application grows, you might,
03:02you might feel like you just need more.
03:04So in that case, I just wanted also you, for you
03:07to be familiar with the different constructs of React Redux
03:10because that is something that the
03:11official documentation supports.
03:14And in this context, what we're gonna do is we're gonna wrap
03:16up our button that we've just created
03:19and create a, a sort of, kind
03:21of like a contextualized button that converts the context
03:24or the state and converts that state into an actual
03:29the features and the
03:30properties that we actually want to get.
03:31So in this case, it's gonna be our props.
03:33That's gonna be the properties that are being sent.
03:36And I could have here in on click
03:38and I could have here our counters
03:41and let's go ahead and implement it.
03:43So first of all, the first step that we want
03:45to implement is I'm gonna go ahead
03:46and create here a constant,
03:47and I'm gonna call it Map State two props.
03:52And as the name implies, this is a function
03:54that is gonna be called by the connect function
03:56that we're gonna be approaching in a minute.
03:59And what it's gonna do is gonna fetch out
04:00of our state itself.
04:02It's going to ba basically send us a state into this
04:05function and it's gonna expect
04:07to get basically a reduced item that will return
04:10what we're actually concerned about.
04:12In our case, I don't really need the whole state,
04:14so I'm literally just gonna extract out of it the counters
04:17and literally I'm just gonna return our counters inside
04:22of an object, making sure that it's gonna be keep,
04:24it will keep its naming convention.
04:26So once it's down here, it will be actually called counters
04:29and it's not gonna be a loosey goosey item
04:31that would be in conflict.
04:34So that's it. Okay, so that's our props.
04:35We also wanna get here an on click
04:37and we wanna get our on click to already set, set up
04:41being capable to create dispatches.
04:43So we don't need to dispatch things on our own.
04:46So the next method, the next constant
04:48that we're gonna create here is gonna be map
04:53dispatch to props.
04:54And by the way, these names are not important.
04:56You could come up with whatever names you want.
04:58The only important thing is that you could, that you know
05:01that this function has the dispatch connected to it.
05:04So then we could then return specific properties
05:07that we would wanna have in our, in our new component.
05:11And there we're gonna say, okay, I want an on click.
05:14And in an on click I wanna create something.
05:17So in this case, our on click method here is going to do,
05:21let's say a dispatch of add counter.
05:25But in our case, because our ad counters are already
05:29dispatching, we actually want the add counter action.
05:32So add counter action is going to be what we're gonna
05:36call trigger, get our actual properties, and then dispatch.
05:41And we just wanna make sure
05:42that we're using our A counters action instead.
05:45Last but not least, now that we have a button, we have our,
05:49the properties that we want from the state,
05:51we have also the dis the dispatching properties that we want
05:55to add into our, into our element.
05:58All that's left for us to do is in our last step is
06:00to go ahead and combine the mold together.
06:02So I'm gonna go ahead and create a new button
06:05and I'll call it button context.
06:08And our button context is literally gonna connect first.
06:11So first of all, we're gonna call our method sending in our
06:13two properties map state to props
06:17and map dispatch to props.
06:20And automatically this function is a carry on function,
06:23which means that we're gonna trigger it one more time
06:25immediately after sending in the visual
06:28component in this case our button.
06:30So what we've done here is literally we,
06:32we basically wrapped up our button
06:34and basically converted the state
06:37into dispatching properties and properties of here.
06:40And by the way, you could, if you don't have anything
06:42that you want to connect, you could just pass your null,
06:44which is completely fine.
06:47And last
06:48but not least is uh, we need to actually run it.
06:52So I'm gonna go ahead into my but in context itself
06:55and I'm gonna go ahead and replace our button here
06:58with a but in context.
07:02And if everything worked according to plan,
07:05our application should work.
07:06And if it didn't, it won't. So let's see.
07:08But a valid react element or null must be returned.
07:11Oh, so I'm not returning actually anything in
07:13that function in our button itself.
07:15I forgot to actually have your uh, return
07:18'cause I added there a curly bracket.
07:20So lemme go ahead and save that. And there we go.
07:23Our application is running again
07:24and we can even add everything
07:27and everything is continuously working.
07:28And we can see that we have your two items already,
07:31two adders as well added into our application.
07:36Now I wanna just go over this quickly
07:37because we did quite a lot.
07:39So first of all, it all relies on our connect.
07:42And by the way, yes, it does mean that you could get rid
07:44of a lot of things, but we're not gonna do that.
07:45We're gonna leave that for you. So you could see all the
07:47different variety of ways you could work.
07:49Secondarily, the connect method is a carry on method
07:53that expects two properties.
07:54The first one are all the states that we actually, the,
07:58the states that we wanna convert into properties.
08:01The second one, and by the way, if we don't want to,
08:02don't need to, we could just send your null
08:04and it will just not send in anything, not convert anything,
08:07which is completely fine.
08:09Same applies for our dispatching property.
08:11So we could decide that we don't want
08:13to in any one of those cases.
08:14In our case, we definitely wanted props
08:16and we definitely wanted oto dispatchable properties
08:19and we connected our connect.
08:21Once that is is done, we wanna also call in the visual layer
08:24that's actually gonna get this information.
08:26And in our case, it's our button
08:28that we've just created here above and send it it in.
08:31And that's it. That's all we have to do
08:33to create these contexts.
08:34The more times you do this, the easier it'll become.
08:36And that's it. That's how you use the React redux
08:41Connect method.
08:44So in this lecture, our last of this title, we learned how
08:47to use really fully the core features of React
08:51and React well React, Redux, and Redux.
08:55Um, and with that said, we're done with this title
08:58and I hope you had a really, really wonderful time.
09:00If you did, please add a comment and a review
09:03and share with a friend.
09:05And if you ever have a question
09:06or wanna follow up, my email is ben@zerotogeek.com
09:12and you could find me also on Twitter,
09:13although I'm rarely ever there.
09:15And my, uh, nickname would be Zero to Geek as well.
09:20And with that said, I bid you a do.

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!