Store a Token Globally with React Context for Easier Use Anywhere in a Next.js App

Vladimir Novick
InstructorVladimir Novick
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Storing token in the state is not the best idea, so you will migrate from storing the token in local state to a global state. For that you will use React context. With React Context, your token can be easily access from anywhere in the app. You will need that for API calls to Symbl.ai later on.

Instructor: [0:00] Let's switch from using local state to custom hook that we'll create. We'll call it useAuth. I'll put it inside hook's directory that we need to create. Let's create our index.js file in your hook's directory. We'll import createContext, because eventually we want to store our token on the context, so createContext/useContext.

[0:28] We'll export authContext, creating context is empty, initially. Then, we'll also export an authProvider that we'll use later on to wrap our app. Then, the authProvider will have the same functionality that we had within the component. Having token and setToken. We use state for that. We will return the context provider, and as a value, we'll provide token and setToken.

[1:05] We'll render children as its descendants, and we'll export our custom hook, useAuth, using useContext and passing AuthContext within. Let's switch setToken and token to be structured as object structuring. We still see that there is a problem. The reason for that because useAuth has to be a function that will return useContext.

[1:39] The reason it's failing because we haven't propped our app with AuthProvider. As I told you, now we'll import AuthProvider from hooks. We'll grab it and wrap the whole app with AuthProvider. As you can see here, if we go and copy our appID and appSecret as previously, the same functionality happens. We have access token print to console and we have our screen rendered here.

egghead
egghead
~ 41 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today