CodeBlanks Logo Icon CodeBlanks

Auth context

Learn authentication with an Auth context.

Auth context

In a mobile app, when the user signs in we want to know this in every screen. Passing a user prop down to every screen is tiring. We use the React Context API instead: an AuthContext keeps the authentication state central.

To create a context you call createContext with a default value. A parent component wraps children with a Provider; the value prop is then available to all descendants. This way login, logout and the user state are managed from one place.

Start with createContext

You create the context with const AuthContext = createContext(defaultValue). The default value is used when no provider exists; usually it is null or an empty object. A common export is export const AuthContext = createContext(null).

To read the context from a child component you use useContext(AuthContext). This hook returns the value of the nearest Provider above. By giving the provider value={{ user, login, logout }} you expose these to the whole app.

Practice Create the AuthContext

Complete the empty file. Import createContext from React. Define export const AuthContext with createContext(null).

Starter code

App.js
import React from 'react';

// Define AuthContext with createContext

Sample solution

App.js
import React, { createContext } from 'react';

export const AuthContext = createContext(null);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does an auth context make easier?

  • Only downloading files
  • Only defining styles
  • Only playing animations
  • Sharing the authentication state across all screens Correct answer

Explanation: An auth context shares the authentication state across all screens.

2 Write the createContext call

Question
export const AuthContext = ____(null);
Answer
export const AuthContext = createContext(null);

Explanation: createContext creates the context.

3 Match each part to its role

Term Meaning
createContext Creates the context
Provider Carries the value top-down
useContext Reads the value below
value Data the Provider carries

All lessons in Advanced