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 4 years ago
Updated 4 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.