Chris Achard: I have some user information being created with a useState hook call. I want to give other parts of my application access to that.
I'm going to create a UserContext with React.createContext. Then I need to wrap my app in that UserContext.Provider. To that provider, I have to pass a value.
The value I'm going to pass is the object containing user and setUser that I get from this useState. If I had a different component called UserDetails, and here I wanted to return the user's name, then first I could import useContext from React.
Then I could pull out the value from the context called UserContext. This context may come from a different file, but right now it's just defined in the same file. Its value is going to be the same thing we defined down here. It's actually the object containing user and setUser.
I'm going to pull those out by destructuring them. I can use this value directly to show the user name. If I take this component and use it in my app and save it, now I can see the value Me, which comes from here, it's pass through this context. I'm using useContext to pullout. Not only that though, but we can set the user with setUser.
Let's say we had another react component called login. Let's give that an input. We're going to make a login form here. We're going to do the same thing. We are going to pullout the current user and the setUser from the context UserContext.
Because we have an input here and we want to make it a controlled component, we also need an interim value. I'm going to call that loginNme and setLoginName. That's just regular useState.
On the input, I can set the value to loginName. On change, I want that to set the login name to the e.target.value. The placeholder can just be login name. We can make a button called login. On the click of that button, that's where we're going to use this setUser function. We can call setUser with the current loginName.
Now we could use this down here. If the user exists, then we can show the user details. Otherwise, let's show that login form. We have to remove this default value to see that so we can save it, and now we get the login form.
If I type my name and click login, then I can see my username. We could also use that setUser function up here. Say we wanted a logout button, we could say logout, and the onClick for that button would just have to set the user to null. Let's save that.
We can login. We get our user information, and we can logout, taking us back to the login page.