Advanced Hooks 8 exercises
Problem

Strongly Typing React Context

Here's a createRequiredContext function that I use in almost every React project I work on:


const createRequiredContext = () => {
const context = React.createContext(null);
const useContext = () => {
const contextValue = React.useContext(context);
if (contextValue === null) {
th

Loading exercise

Transcript

00:00 Here I'm going to show you a function that I copy over to basically every project I do in React, and also that I've seen a bunch in the wild as well. This function is called createRequiredContext. This basically creates a new context, creates a useContext hook,

00:15 and then returns them, basically returning the useContext hook and the context.provider. In the useContext, we're doing something interesting, which is we're basically saying, What we're doing here is we're saying if there is a context value here that could be null, because we're actually creating the context as null,

00:33 then we're saying throw new error context value is null. This means that we always get the actual context being returned here. So useUser, for instance, which is basically a hook to grab the user's name out of the global provider. Imagine that this global provider, then we go and grab that and stick it in,

00:52 you know, our app.tsx or something. And inside here, we've got useThemeThemeProvider. We're expecting this user here to be a type of user, right? But instead, we're actually getting React.ReactNode here. That's bizarre. And same theme here, too. We're getting React.ReactNode. How on earth can that be right?

01:11 useUser here appears to be a function that returns never or React.Provider null. There's a bunch of stuff happening here. And ideally here, inside here, we should be able to pass in a name mat here inside the top level parent, let's say. So there's just so much that's going wrong here. And see if you can fix it.

01:30 You should be able to fix it just by changing this function here. You notice we're going to need to be able to pass in type arguments or just one type argument into createRequiredContext. We're going to need to do a few more things. And just, yeah, you're going to get a sense for how to strongly type this, I think, just by messing about with it a little bit.

01:49 So that's your job. I think I've given you all the information you need. There's a bunch of errors to solve. Good luck.