Search⌘ K

Context API

Explore how to implement the React Context API to manage global state in a full-stack application. Understand how to configure context, set initial state, utilize reducers, and create context providers to handle authentication and user data. This lesson helps you build scalable client-side features without prop drilling by using React’s built-in hooks.

Context API, a built-in service in React, handles the state globally so that we can access it anywhere in our application. A well-known example of data that needs to be global is the currently authenticated user. Context API helps us easily control what renders to the guest and what is hidden.

Context API configuration

To start configuring the API into the application, we need to initialize an instance of the Context.

Javascript (babel-node)
// frontend/src/context.js
// Import the built-in createContext hook from "react"
import React, { createContext } from "react";
// Create the appliation context, you can name as you like.
export const Context = createContext();

Initial state

Then, we need to define an initial state, which works as the default value for the application:

Javascript (babel-node)
// frontend/src/context.js
// Import the built-in createContext hook from "react"
import React, { createContext } from "react";
// Create the appliation context, you can name as you like.
export const Context = createContext();
const initialState = {
auth: false,
user: null,
token: null,
};

We defined an object with these three fields:

  • The ...