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.
SignIn: Represents the sign-in step.SignUp: Represents the sign-up or registration step.ForgotPassword: Represents the "forgot password" recovery step.ResetPassword: Represents the password reset step.VerifyEmail: Represents the email verification step.
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
step: Step— The target step to switch to, from theStepenum.
Returns
An object containing:
switchStep: () => void— A function that, when called, updates thestepquery parameter in the URL to the specified step.
How It Works
Uses
useSearchParamsfromumito get and set URL query parameters.Defines a memoized callback
switchStepusinguseCallbackthat sets the URL parameterstepto the string representation of the provided step.Returns the
switchStepfunction, which can be invoked by any component to trigger the URL update.
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
The hook leverages
useSearchParamsfrom theumiframework, which is an abstraction over the native browser URLSearchParams and React Router's location management.The
stepvalue is converted to a string using.toString()to ensure it is suitable for URL parameters.The
switchStepfunction is memoized to avoid unnecessary re-creations on component re-renders unlesssteporsetSearchParamschanges.The hook logs the current search parameters to the console for debugging purposes (
console.log), which could be removed or replaced with a more sophisticated logging mechanism in production.
Interaction with Other Parts of the System
URL Query Parameters: The hook directly manipulates the URL query string, specifically the
stepparameter, to reflect the current authentication step.Routing and State Management: Other parts of the application—such as authentication components or pages—can read the
stepquery parameter from the URL to decide which UI to render.umiFramework: This hook depends onumi'suseSearchParamsfor handling URL parameters, making it specific to applications built with theumiframework (or compatible routing mechanisms).Authentication Pages/Components: Components responsible for rendering the different authentication steps (sign-in, sign-up, etc.) will likely use this hook or the
stepURL parameter to control their displayed content dynamically.
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:
The
useSwitchStephook internally callsuseSearchParamsto gain access to URL parameter setters.It defines a
switchStepcallback function that updates the URL'sstepparameter to the specified authentication step.This flow illustrates the relationship between the hook, the internal
useSearchParamshook, and theswitchStepfunction used by components.