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

Understanding React Context and Why to Avoid It

Using React Provider: A Tutorial

In this tutorial, we'll cover how to use the React Provider, particularly when using Redux, to share data across components without passing props manually at every level.

What is the Provider?

The Provider is a special component that comes from the React Redux library. It allows you to wrap your entire application (or specific parts of it) to give all child components access to the Redux store, without having to manually pass it through each level of components.

Step 1: Installing React Redux

Before we can use the Provider, we need to install the React Redux library. You can do this using npm or yarn:

npm install react-redux

or

yarn add react-redux

Step 2: Importing the Provider

Once installed, you need to import the Provider from React Redux. Open your main JavaScript file, usually index.js or App.js, and add the following import:

import { Provider } from 'react-redux';

Step 3: Wrapping Your Application with the Provider

To make the Redux store accessible to all components, you need to wrap your root component with the Provider. The Provider requires a store prop, which will be the Redux store you have created.

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Step 4: Understanding Why the Provider is Useful

In a large application, passing data through props can become cumbersome, especially if you have deeply nested components. The Provider component solves this issue by making the Redux store available to any nested components that need it, regardless of how deep they are in the component tree.

Without Provider, every time you need to use the store, you would have to pass it manually as a prop from one component to the next, which is not scalable.

Step 5: Accessing the Store in Child Components

To access the Redux store from a child component, you need to use the connect function, which is also provided by React Redux. Alternatively, you can use the useSelector and useDispatch hooks for functional components:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

const MyComponent = () => {
  const myData = useSelector((state) => state.myData);
  const dispatch = useDispatch();

  const handleClick = () => {
    dispatch({ type: 'MY_ACTION' });
  };

  return (
    <div>
      <h1>{myData}</h1>
      <button onClick={handleClick}>Dispatch Action</button>
    </div>
  );
};

Best Practices and Warnings

The creators of React generally recommend avoiding using the React context directly for state management in large-scale applications. Instead, they suggest using well-established libraries like Redux that provide a more stable and efficient way to manage state.

The Provider component uses React context under the hood, but the abstraction that Redux provides makes it much easier to work with, especially in larger projects. By using Redux and the Provider, you gain a predictable state container with easy debugging and tools that make development smoother.

Summary

  • Provider: Wraps your application to give all components access to the Redux store.
  • Installation: Use npm install react-redux to install the library.
  • Usage: Import Provider and wrap your root component.
  • Accessing Store: Use useSelector and useDispatch hooks or connect to interact with the store in child components.

The Provider is an essential part of working with Redux in React. It ensures that your components can access the global state efficiently, and helps you avoid the "prop-drilling" problem where props need to be passed through multiple levels of components.

In the next part of this tutorial, we will explore the connect function in more detail and learn how to use it as an alternative to hooks, especially in class-based components.

Video Transcript

00:00Generally speaking, the creators of React suggest
00:03that you don't use the context,
00:04but I want you to be familiar with it
00:06because that's probably,
00:07and not only probably it's what's going on
00:10behind the scenes, although the solution,
00:12we have a better solution,
00:13which we'll cover in the next lecture.
00:15It's one that you want to be familiar with,
00:16especially if you're looking at other people's code.
00:19So with that said, we're gonna take a look at how to work
00:21with the context and literally why you wanna avoid it is
00:24simple, it's not stable and there are better solutions.
00:27So you probably don't want to use it in a real world app,
00:30but let's take a look at how you work with it
00:32so you'll know also how to avoid it
00:33and also know what it is if you ever see it.
00:38And well, you're better off using a library,
00:40which we're gonna talk about
00:42that in the next lecture from the React Redux,
00:44which provides a solution.
00:46Now, you wouldn't be wrong to assume
00:48that this uppercase does imply to us
00:51that it's probably a React component.
00:53And it's true, it's a component
00:54that actually does some really cool stuff behind the hood
00:57that we're not gonna get into.
00:58But if you check the
00:59provided links, you'll understand what's actually happening
01:03behind the hood really.
01:05Okay, so what we wanna do with the provider,
01:07we literally wanna wrap up our full application with it.
01:10And what am I doing?
01:12We wanna wrap up our full application with it.
01:15So let's go ahead and what's going on with my keyboard?
01:18It's completely going crazy. Oh yeah, because you know what?
01:21I didn't copy that. That would do it. Okay, so there we go.
01:26And we wanna also make sure that we close it.
01:31Beautiful. So that's the basics of
01:34what we need to do with our provider.
01:35And the next step is to actually give it the store itself,
01:38the full store, not an actual state.
01:41So I'm gonna go ahead here
01:42and literally provide to it the full store.
01:45Now once I do that, it's gonna make our application not work
01:48anymore, but we'll fix that in a minute
01:50'cause we're not gonna be sending our data anymore
01:52to our application.
01:54Now again, if you ask yourself why would you do this,
01:56you would do this in a scenario where you have a lot
01:59of components, it's a big application
02:01and you don't wanna need a pass around data from component
02:04to component manually.
02:05'cause a lot of situational will happen
02:06where you have components that are literally just a visual
02:09layer and in between them.
02:10Then suddenly there's some sort of component
02:12that needs actual data
02:13that's coming from the store itself while at other
02:15situations where it doesn't.
02:18With that said, we, let's just also make sure
02:20that we're gonna adhere to that inside of our testing
02:23for our app text test.
02:25'cause there we're literally going through the whole app.
02:27So I'm just gonna go ahead
02:28and copy this whole structure here
02:31and send it into our test as well.
02:33So our test won't fail down the line.
02:35Now we're almost done, but we're not done yet.
02:38We have one more thing that we need to do to be able
02:40to connect it all together.
02:42So to do that, I'm gonna go into my app itself this time
02:44around and not the index.
02:46And in the app itself, I'm gonna declare
02:49that I want access to it.
02:50Now, by the way, just
02:52because you could have children that have the content,
02:55it does not mean that the children will have access
02:57to the store to
02:58Give, give them that access.
02:59You actually have to declare and ask for that access.
03:03To do that, literally
03:04what you're gonna do is you're gonna go ahead
03:05and you're gonna add into your component itself.
03:08As before it's instantiated obviously,
03:11'cause we're not instantiating it.
03:12And we're gonna go into our context types
03:15and declare the contexts that are going to be available.
03:19In our case, it's gonna be store
03:21and we wanna declare what type that is.
03:23So it's react dot prop types object.
03:28And what we're literally saying is expect to get a store
03:31and it's gonna be a type of object.
03:33Now once we have that plugged in,
03:35and by the way, we're gonna show you how to get rid of this.
03:37'cause this is kind of like a almost hidden feature in React
03:41one that conventionally you don't really want
03:43to use directly because it could change at
03:45any point, at any time.
03:47So we're gonna change this in the following lecture,
03:49but let's see, how would we work with our context?
03:51Just so you know a little bit of the connection
03:53between what's happening behind the hood.
03:55So now when we're doing that, we're gonna have
03:57to create here another variable.
03:59So I'm just gonna go ahead here. Access our store as well.
04:03Um, actually we're gonna get our store
04:07and from our store itself,
04:09I'm literally gonna get it from our this dot context.
04:14Now that I have access to the store itself,
04:16I'm not gonna actually approach our props anymore
04:18'cause it's not being sent to the props.
04:20But instead of that, I'm gonna ask for it to, for its state.
04:23And once I got this state,
04:24literally I'm selling sending in the full store
04:26and then I could fetch out of it the data
04:28that I wish to get out of it.
04:30In this case, it's the whole data bucket.
04:33So once I've done this theoretically,
04:34at least everything should work
04:36unless we have some error going on here.
04:37So let's see, what is our error?
04:39So, uh, provider not not defined, which is true
04:43because in our test itself we did not provide our provider.
04:47So let's go ahead and also incorporate our provider inside
04:51of our test itself as well.
04:53And let's take a peek again
04:54to see if we still have errors in.
04:55There we go. Our errors are, are, are away,
04:58at least in the developer, in the in,
05:01in the just environment, uh, failed prop types.
05:04The prop store is marked as required in provider,
05:07but it's value is undefined.
05:09So let's uh, trace this back
05:10and figure out what am I doing wrong?
05:12Let's start from our app itself. And in our app itself.
05:15Are we in our index itself? Are we sending in our store?
05:19We sure are. And that is
05:23incredibly surprising.
05:24So let's see, do we have your anything in our terminal?
05:27No, that looks all good.
05:29So let's read this error a little bit more explicitly.
05:33So warning failed, prop type. Prop type.
05:37The prop store is marked as required in provider,
05:41but its value is undefined,
05:47which is literally what it's actually telling us is that our
05:51provider itself is actually not getting the store
05:54that it's expecting to get. Maybe I did
05:56Not save those.
05:57Could it be? No, of course I saved it.
06:01That is some crazy, oh yeah, I didn't save it.
06:04You know that. Ugh, I hate when I do that.
06:06Okay, so there you go. Our component is working.
06:09Um, unfortunately debugging, even
06:10with the best debugging tools, you don't save.
06:13Well, you have a problem.
06:14You know, if anyone from the team at Sublime Checks ever
06:17watches this video, please do something about that
06:21because it's so incredibly hard to see
06:23that this file has changed and was not saved.
06:26If they would only add into this, into the default features
06:28where maybe the tab changes the color or you have a asterisk
06:31or something, that would imply to us that it,
06:34the file is not saved.
06:35Okay? So if you work there
06:36or you know someone that works at Sublime Text, tell them
06:39to add that in as the default of the application.
06:42I would really appreciate it.
06:43With that said, we got our application
06:45to work and we're almost done.
06:46We really just wanna solve, one last thing
06:48before we wrap this title up is, how do you get rid
06:51of using this context directly?
06:53And we're gonna cover that in the following lecture.
06:56In this lecture we saw how to do it the wrong way
06:59because it's not a stable way.
07:01In the next lecture we're gonna take a look at how
07:03to use Connect method instead.
07:05And it's a really great mechanism to work
07:07with if you go in this path.

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!