Understanding React Context API with TypeScript

Jahid Momin
2 min readMay 26, 2024

--

created by canva

What is the Context API?

The Context API in React allows you to create global variables that can be passed around your app. This makes it easier to manage and share state across multiple components without prop drilling.

Why Use the Context API?

The Context API is useful when:

  • You have global data that needs to be accessed by multiple components.
  • You want to avoid passing props down through many layers of the component tree (prop drilling).

Setting Up the Example

Let’s break down the code into manageable parts to help you understand how to use the Context API with TypeScript easily.

Step 1: Create the User Context

First, we need to create a context to hold our user data. We’ll use TypeScript to define the types for our user and the context.

// UserContext.tsx
import React, { createContext, ReactNode, useContext, useState } from 'react';

type AuthUser = {
name: string;
email: string;
};

type UserContextType = {
user: AuthUser | null;
setUser: React.Dispatch<React.SetStateAction<AuthUser | null>>;
};

const UserContext = createContext<UserContextType | undefined>(undefined);

type UserContextProviderProps = {
children: ReactNode;
};

export const UserContextProvider = ({ children }: UserContextProviderProps) => {
const [user, setUser] = useState<AuthUser | null>(null);

return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};

// Custom hook to use the UserContext
export const useUserContext = () => {
const context = useContext(UserContext);
if (!context) {
throw new Error('useUserContext must be used within a UserContextProvider');
}
return context;
};

Step 2: Wrap Your App with the Context Provider

Next, we’ll wrap our main App component with the UserContextProvider to make the user context available throughout the app.

// Main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import { UserContextProvider } from './context/UserContext';
import './index.css';

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<UserContextProvider>
<App />
</UserContextProvider>
</React.StrictMode>,
);

Step 3: Create a Component to Use the Context

Now, let’s create a component that uses the context. We’ll create AuthUser to manage the login and logout functionality.

// AuthUser.tsx
import { useUserContext } from "../context/UserContext";

export const AuthUser = () => {
const { user, setUser } = useUserContext();

const login = () => {
setUser({ name: 'John Doe', email: 'john.doe@example.com' });
};

const logout = () => {
setUser(null);
};

return (
<div>
<button onClick={login}>Login</button>
<button onClick={logout}>Logout</button>
<p>User: {user ? user.name : 'No user logged in'}</p>
</div>
);
};

Step 4: Using the Component in Your App

Finally, we’ll use the AuthUser component in our App component.

// App.tsx
import React from 'react';
import { AuthUser } from './components/AuthUser';

function App() {
return (
<div className="App">
<AuthUser />
</div>
);
}

Lets follow ,Share , Happy coding!

--

--

Jahid Momin
Jahid Momin

Written by Jahid Momin

Team Lead | Sr Software Engineer | Spring boot | Microservices | JavaScript | CodeIgniter | HTML | CSS | ReactJS | NextJS | Youtuber | Writer

No responses yet