How to Use the Context API in a Next.js TypeScript Project
The Context API is a powerful tool in React that allows you to share data between components without having to pass props down through each level of the component tree. It's especially useful in a Next.js project, where you might have multiple pages that need access to the same data.
In this tutorial, we'll show you how to use the Context API in a Next.js TypeScript project to share global variables between pages. We'll create a context for a sessionKey
variable and make it available globally, and then show you how to add another variable called merchantKey
.
Prerequisites
To follow along with this tutorial, you'll need:
A basic understanding of React and Next.js
A Next.js TypeScript project set up
Setting up the Context
To get started, let's create a context for the sessionKey
variable. In your Next.js project, create a new file called SessionContext.tsx
in the src
directory. This file will contain the context and its provider.
import { createContext, useContext, useState } from "react";
type SessionContextProps = { sessionKey: string; setSessionKey: (key: string) => void; };
const SessionContext = createContext({ sessionKey: "", setSessionKey: () => {}, });
export const useSessionContext = () => useContext(SessionContext);
export const SessionContextProvider = ({ children }: any) => { const [sessionKey, setSessionKey] = useState("");
const contextValue = { sessionKey, setSessionKey, };
return <SessionContext.Provider value={contextValue}>{children}</SessionContext.Provider>; };
In this file, we define a new context called SessionContext
that has a sessionKey
property and a setSessionKey
function. We also create a new useSessionContext
hook that we can use to access the context in our components.
Finally, we create a SessionContextProvider
component that wraps our app and provides the context to all of our components.
Using the Context in a Component
Now that we've created the context, let's use it in a component. In a new file called MyPage.tsx
in the src
directory, we'll create a new component that displays the sessionKey
and a button to set it.
import { useSessionContext } from "./SessionContext";
const MyPage = () => { const { sessionKey, setSessionKey } = useSessionContext();
const handleButtonClick = () => { const newSessionKey = "some_new_session_key"; setSessionKey(newSessionKey); };
return (
Session Key: {sessionKey}
Set Session Key
export default MyPage;
In this component, we import the useSessionContext
hook from our SessionContext
file and use it to access the sessionKey
value and the setSessionKey
function.
We also define a new function called handleButtonClick
that sets the sessionKey
value to a new value when the button is clicked.
Wrapping the App with the Provider
Finally, we need to wrap our app with the SessionContextProvider
component so that our components can access the context. In your pages/_app.tsx
file, import the SessionContextProvider