Share Authentication & Appwrite Session State Globally with React Context

Share this video with your friends

Send Tweet

Our authentication system is pretty solid and works well, but if we try to start using it anywhere other than the one spot we’ve used it so far, we’re going to be copying and pasting the same request over and over within the application. On top of that just being a pain to manage, we’ll also be making duplicate, unnecessary requests that just waste time and bandwidth.

React gives us a few options for how we can mitigate this. Particularly, we’ll be looking at the Context API, which will allow us to easily access state in components that are defined in the same tree as whatever component we wrap with that Context, such as the root of the app, meaning all components will be able to access that Context.

In this lesson, we’ll walk through all the bits of how to make this work, which includes creating a new hook where we define that Context and the Provider which will wrap our application. We’ll then define and set up Types for the state that we’ll pass through our context, migrate our auth-related requests to this new hook, and dynamically update our UI to make use of our new hook including our login flow, hiding the Add Event for guests, and even redirect user’s away from pages that require authentication.

What You’ll Learn

  • Create a new React hook
  • Set up a new instance of Context using createContext
  • Define Types for application Context
  • Create a Provider that allows us to access our Context globally
  • Manage global state with useState and pass it through app with Context
  • Request, store, and manage a user’s Session globally
  • Dynamically show and hide UI based on global auth state

Resources