hooks.ts

Overview

The hooks.ts file provides a lightweight, reusable React hook utility designed to manage and synchronize authentication-related workflow steps with the URL's query parameters. It primarily facilitates switching between different user authentication states (such as Sign In, Sign Up, Forgot Password, etc.) by updating the step parameter in the URL using umi's useSearchParams hook. This enables deep linking and browser navigation support for different authentication views within a React application.


Detailed Explanation

Enum: Step

export enum Step {
  SignIn,
  SignUp,
  ForgotPassword,
  ResetPassword,
  VerifyEmail,
}

Description

The Step enum defines the possible states or steps in the authentication flow. Each member corresponds to a specific step or screen in the user authentication process.

Usage Example

const currentStep = Step.SignIn;

This enum is used to strongly type the step parameter in the useSwitchStep hook.


Hook: useSwitchStep

export const useSwitchStep = (step: Step) => {
  const [_, setSearchParams] = useSearchParams();
  console.log('🚀 ~ useSwitchStep ~ _:', _);
  const switchStep = useCallback(() => {
    setSearchParams(new URLSearchParams({ step: step.toString() }));
  }, [setSearchParams, step]);

  return { switchStep };
};

Purpose

useSwitchStep is a custom React hook that returns a function to update the URL search parameter step to the specified authentication step. This allows the application to reflect the current authentication UI state in the URL, supporting direct linking and back/forward navigation.

Parameters

Returns

How It Works

Usage Example

import React from 'react';
import { Step, useSwitchStep } from './hooks';

const AuthNavigator = () => {
  const { switchStep } = useSwitchStep(Step.SignUp);

  return (
    <button onClick={switchStep}>
      Go to Sign Up
    </button>
  );
};

In this example, clicking the button updates the URL query parameter to ?step=1 (assuming SignUp corresponds to 1), signaling the app to show the Sign Up screen.


Implementation Details


Interaction with Other Parts of the System


Summary

hooks.ts provides an enum and a custom hook for controlling authentication flow steps via URL query parameters. This design enhances navigation and state persistence by encoding the current step in the URL, enabling better user experience with browser navigation and direct linking capabilities.


Visual Diagram

flowchart TD
    A[useSwitchStep(step: Step)] --> B[useSearchParams()]
    A --> C[switchStep() callback]
    C --> D[setSearchParams(new URLSearchParams({ step }))]

    classDef hook fill:#f9f,stroke:#333,stroke-width:1px;
    class A hook;

Diagram Explanation:


End of Documentation for hooks.ts