Check out a free preview of the full React and TypeScript course:
The "Context API" Lesson is part of the full, React and TypeScript course featured in this preview video. Here's what you'd learn in this lesson:

Steve demonstrates how to move state management to the Context API using a ThemeContext to create a light mode and dark mode for the application. When React renders a component that subscribes to the created Context object it will read the current context value from the closest matching Provider above it in the tree. A student's questions regarding what keys there are other than strings is also covered in this segment.

Get Unlimited Access Now

Transcript from the "Context API" Lesson

[00:00:00]
>> So the other kind of core piece of React that we need to think about is the context API. And a lot of the other things that we saw using the context API, in its happy path, super easy, right? The issue we have with the state before, which is what happens when we don't necessarily know everything beforehand?

[00:00:31] With use state, we pass in a number. It's like cool, this state is number, only take numbers for updating it, neat. Think about the context API that we'll have to deal with. And second is but even without it being asynchronous, per se, by the very nature of the way that it works in React.

[00:00:47] There's lots of situations where we might not have everything we need at the time. But let's work through a kind of happy path first, just to see what it looks like and how to work with it. So we've got a little bit more complicated, but still simple on the grand scale of things application here of that just creates a color swatch based on red, green and blue.

[00:01:11] It's got some sliders. It's got some inputs. It takes a div. It changes the background color. What we wanna do is we're gonna do two things. One, we're gonna eventually refactor [INAUDIBLE] passing down the colors all the way through. And we're also going to give it a dark mode, because that seems to be in vogue these days.

[00:01:30] And theming is one of usually the core use cases of the context API. There's a state management piece as well that is frequently used. But the naming gives us a little bit of a happy path to start with here. So we'll start with that just to get just one, the context API, especially setting up a context.

[00:01:50] Using a context, you do all the time once you have it set up. Setting up a new context, a lot of times, is something you don't do often enough. You set it up once, and you use that context throughout your application. So I think just getting the muscle memory back around setting that up.

[00:02:07] So in this project, we're gonna make a new file. I'll call it ThemeContext. And ThemeContext, let's fork it. We've got a completed one. We'll fork this one. I can save, and stuff like that. And we'll import React. And React has createContext on it. We can actually do it inline if we want.

[00:02:41] And we'll kinda take a look at this. We can make a new context. CreateContext, and we'll give a light mode, which will have a background color of white, and make the text white. And basically, what we have now. And we'll give it a dark mode. That'll have a darker background color, I'm thinking.

[00:03:15] Let's go with, Dark gray there, and we make the text white. Now, this is gonna behave not in a dissimilar fashion for when we did use state before. Which is TypeScript was looking at what we passed in as the initial value of that context, and effectively made a type on the fly for us, right?

[00:03:40] So you can see, okay, the context should be an object that takes a light and a dark, and each one of those has a background color that's a string, and a color that's a string. And we could say something like type is theme. And maybe that's got a background color that is a string and a color.

[00:04:06] That's a string. And then we could say something along the lines of type themes. And I think we saw this in one of the previous slides. I can be like, listen, we can have as many different keys, or whatever in this case, like colors, names, whatever. They should be strings, and the value should be a theme, right?

[00:04:31] And then we could pull this out, As well. We'll call this maybe a const defaultTheme. And we'll say that this default theme should be of the type themes. See if I got that right, I did. And so now we can pass in default theme. And again, TypeScript figured it out on the fly, but now I could have additional themes that are not just light and dark that I could add later.

[00:05:02] I'm not going to, but just to kinda show you how that might work. The other thing I could do here is I could actually just say that these are, Any CSS properties could go in there as well and get rid of just a singular theme, right? So now the idea of a theme is an object that has any key as a string, in this case, light and dark.

[00:05:22] And then from there, we'll take anything conforms to reacts CSS property. So still, we're giving type information to TypeScript, but we're still pretty flexible in how we define that as overtime as our application grows and changes, and stuff along those lines. So we've got that in place. We've got our themes.

[00:05:43] Now we need to create the theme provider that we wrap around our application. And so here, we'll say we're gonna need to export this as well, eventually. And we'll also export a theme provider. And that is gonna take children, and I could do it inline, or I can define it separately.

[00:06:06] We're gonna do it inline. So children we know is of the type React.ReactNode. And that's gonna be a function. That is simply going to return ThemeContext.Provider. The value, it's gonna be my themes, or default theme, and it will render children. Nope, yeah, close that the right way, great.

[00:06:47] Let's see, we've got some red squigglies. I gotta export a const. And everything will work. All right, so we have that in place. And again, that is mostly as a refresher for the context API, as we'll see in the second example, where we have to get a little bit more complicated.

[00:07:02] And I didn't wanna do the refresher at the same time as dealing with some of the edge cases. So we've got that in place. The other thing we need to do is we'll go to our index here, and we'll just wrap the application in that provider. So we'll say, ThemeProvider, pulling the ThemeProvider.

[00:07:29] And then finally, in Application.tsx, we're gonna just use react.useContext. UseContext, and we'll bring in that ThemeContext from before. And now we have access to it in the application. So here I can, for instance, Gotta put a comma in there. We'll give it dark mode. And we can use this throughout our application, as we might expect.

[00:08:14] So that worked, because for a reason we've seen multiple times in this course so far. Which is, well, TypeScript had all the information that it needed, and we didn't even need to define all this extra type here. We chose to do it to give ourselves some flexibility, but it looked effectively at what we passed in.

[00:08:38] You can even see if we hover over createContext, or the ThemeContext itself, that the type is themes, right? And we didn't actually declare it in there. If you look here, it's like, it's very similar if we had said themes, okay, cool. Make sure you give me something that conforms to that object.

[00:08:58] In the absence of that, TypeScript was able to figure that out. One of the questions is what are the other keys other than strings? I mean, you could say it's a number. Also, this syntax works for maps, or a similar syntax works for maps as well, which can have any object.

[00:09:17] Obviously, this doesn't work anymore. The thing about JavaScript is that all the keys are effectively strings anyway. So it's less of a type script constraint, and a little bit more of a how things are under the hood. Maps allow for a wider range of keys. But for what we think about plain old JavaScript objects, you can use numbers is how arrays work.

[00:09:41] Or strings is usually the most common one, in this case.