Intermediate React, v2 useContext
This course has been updated! We now recommend you take the Intermediate React, v5 course.
Transcript from the "useContext" Lesson
>> Brian Holt: So let's go down to use Context, so Context.js right here.
>> Brian Holt: Now, notice I have first level, second level, third level, fourth level, and then I have James Jameson the firstborn. I think I was a couple of whiskeys deep, so that's the most creativity I could muster.
>> Brian Holt: So context is solving this problem. Which, if you need to know more about context, I implore you to take the Intro to React, cuz that talks about context. But just to tell you, it solves the problem of having to do prop drilling of passing parent to child, parent to child, as well as covering things that Redux would normally cover, which is like application-level state.
[00:00:44] So here I'm creating a context with a fake object. This is just letting people know the shape of the object. And this is an updater function. Or this would be called an identity function technically, but not that it really needs to be that. But suffice to say this is the shape of a hook.
[00:01:02] Okay? Here is actually where this matters, here on levelFive, right? Where I create this, well, that's down here at the bottom, so let's actually start all the way down here at the level one. Or ContextComponent, rather. So here, I'm creating a useState hook, right? With the name James Jameson 1 and his email address.
[00:01:28] But I could totally change this to Bob or something like that, right? Notice that would change down here. But I'm creating this in the top-level component. I'm putting this provider above it. And then I'm rendering down to level two. Level three, level four, and then level five here.
[00:01:47] Here I'm reading through the context. Notice I didn't pass it through all these various different levels of components. But I'm reading out of the context here using useContext, all right? So then I get user and set user down here. And here if I click increment, it's incrementing this despite the fact that the hook lives all the way up here.
[00:02:09] So useContext allows you to read and write to context in this fashion.
>> Brian Holt: Any questions about useContext? Again, there’s a whole section on it in the Complete Intro to React. So if context itself is confusing to you, I’d implore you to take a look at that