DEV Community

Elham Najeebullah
Elham Najeebullah

Posted on

React & TypeScript: How to use Context API and useReducer hook by creating authentication basic app.

Here is an example of how you could use React Context and the useReducer hook with TypeScript to create an ecommerce authentication app:

First, you would need to create a context for the authentication state:

import React, { createContext } from 'react';

export const AuthContext = createContext<{
  isAuthenticated: boolean;
  user: User | null;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
}>({
  isAuthenticated: false,
  user: null,
  login: () => Promise.resolve(),
  logout: () => {},
});

Enter fullscreen mode Exit fullscreen mode

Next, you would define the types for the state and actions:

type User = {
  id: string;
  username: string;
  email: string;
};

type AuthAction =
  | { type: 'LOGIN'; user: User }
  | { type: 'LOGOUT' };
Enter fullscreen mode Exit fullscreen mode

Then, you would define the reducer function to handle the login and logout actions:

const authReducer: Reducer<{ isAuthenticated: boolean; user: User | null }, AuthAction> = (
  state,
  action
) => {
  switch (action.type) {
    case 'LOGIN':
      return { isAuthenticated: true, user: action.user };
    case 'LOGOUT':
      return { isAuthenticated: false, user: null };
    default:
      return state;
  }
};

Enter fullscreen mode Exit fullscreen mode

Finally, you would create a provider component to wrap your app and manage the authentication state:

import { db } from './firebase';

const AuthProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, {
    isAuthenticated: false,
    user: null,
  });

  // A function to handle login requests
  const login = async (
  ...
Enter fullscreen mode Exit fullscreen mode

This is just to show you how to use React and Typescript with Context API and useReducer hook not a complete authentication app.

I hope this helps! Let me know if you have any questions or need further assistance.

Top comments (1)

Collapse
 
jeebulla profile image
Yusuf Najeeb

Not beginner friendly. You can more details and why to the blogpost.
In all great job 👏