Instructor: Let's kick up our dev server to run our example React app. On the right, you can see a relatively simple Todo app. You can add, check off, and delete items.
This one has a special toggle in the upper right-hand corner. This controls the theme of the app. There's a dark theme and a light theme. Let's check out the code and see how this is handled.
Let's first go to the app JS file. On line five, the app is using the React Context API to control how the theme is getting passed through the components. In the render, the theme context provider is passing the theme value to its consumers.
The theme changes when the switch component is changed on line 51. The componentDidMount is grabbing the theme value from local storage. The handle theme change is flipping the theme and saving that to local storage as well.
How do we consume the context? In a React class, there are two ways. One is to import the theme context and use render props with the consumer. It'll pass the value, which is the theme, and you can use it how you wish.
It's easier to see if we collapse the code. The consumer expects a function that will get invoked with the theme that then can be used.
Another way to consume context in a React class is to also import the theme context, but this one is much more straightforward. You give the class a context type and assign it to your context. Then when you want to use the context to value, you reference the context property off of this. That's it. This.context represents the theme in this case.
Let's now switch to a function component that mostly has all the theme stuff taken care of. If we kick up our dev server, I'll show you close it is.
On the right, if I flip to the light theme, almost everything looks as it's supposed to, except the border around the ToDos. It should be darker, not a while line.
Let's go into the code and see how to add context to a function component. You might have already guessed it. You import a useContext hook from React.
To leverage the useContext hook, you just create a variable to store the context value and set it to useContext passing the context you want to consume, which in our case is theme context.
Now we can use the theme wherever it is needed. In this case, we need to replace the hard-coded dark value on line 38 to be a theme.
Now we should be able to try the app out again. This time, when we switch themes, it looks much better, or at least as it should be.