common-hooks.tsx
Overview
The common-hooks.tsx file provides a set of reusable React hooks designed to simplify and standardize common UI behaviors and utilities across a React application. These hooks include modal visibility management, deep comparison effect handling, dynamic SVG icon importing, confirmation dialogs for deletions, and translation utilities. By abstracting these common patterns, this file promotes code reuse, consistency, and cleaner component implementations throughout the app.
Detailed Documentation
1. useSetModalState
Purpose
Manages the visibility state of modal dialogs, exposing methods to show, hide, or toggle the modal.
Signature
useSetModalState(initialVisible?: boolean): {
visible: boolean;
showModal: () => void;
hideModal: () => void;
switchVisible: () => void;
}
Parameters
initialVisible(optional, boolean): Initial visibility state of the modal. Defaults tofalse.
Returns
An object containing:
visible: Current visibility state (boolean).showModal: Function to set visibility totrue.hideModal: Function to set visibility tofalse.switchVisible: Function to toggle visibility.
Usage Example
const { visible, showModal, hideModal, switchVisible } = useSetModalState();
return (
<>
<button onClick={showModal}>Open Modal</button>
{visible && <Modal onClose={hideModal}>Modal Content</Modal>}
</>
);
2. useDeepCompareEffect
Purpose
A React effect hook that only triggers when the deep comparison of dependencies changes, unlike the built-in useEffect which does a shallow comparison.
Signature
useDeepCompareEffect(
effect: React.EffectCallback,
deps: React.DependencyList
): void
Parameters
effect: The effect callback function to run.deps: Dependency list for the effect, compared deeply.
Returns
Void.
Implementation Details
Uses
lodash'sisEqualto perform deep comparison of dependencies.Stores previous dependencies in a
ref.Calls the effect only if the dependencies have changed deeply.
Cleanup function returned by effect is handled properly.
Usage Example
useDeepCompareEffect(() => {
// Effect code here, runs only if deps deeply changed
}, [complexObject]);
3. useDynamicSVGImport
Purpose
Dynamically imports an SVG component by its path/name, enabling lazy loading of SVG icons.
Signature
useDynamicSVGImport(
name: string,
options?: UseDynamicSVGImportOptions
): {
error?: Error;
loading: boolean;
SvgIcon?: React.FC<React.SVGProps<SVGSVGElement>>;
}
Parameters
name: The module path or name to import the SVG from.options(optional):onCompleted: Callback when import succeeds, receives(name, SvgIcon).onError: Callback when import fails, receives the error.
Returns
An object containing:
error: Any error encountered during import.loading: Boolean indicating import status.SvgIcon: The imported SVG React component, if available.
Implementation Details
Uses
useEffectto trigger import onnameor callbacks change.Imports SVG asynchronously using dynamic
import().Extracts
ReactComponentfrom the imported module.Calls callbacks accordingly.
Usage Example
const { loading, error, SvgIcon } = useDynamicSVGImport('./icons/MyIcon.svg');
if (loading) return <span>Loading...</span>;
if (error) return <span>Error loading icon</span>;
return SvgIcon ? <SvgIcon /> : null;
4. useShowDeleteConfirm
Purpose
Provides a reusable hook to show a confirmation modal for delete operations, integrated with Ant Design's modal system and i18n translation.
Signature
useShowDeleteConfirm(): (
options: {
title?: string;
content?: ReactNode;
onOk?: (...args: any[]) => any;
onCancel?: (...args: any[]) => any;
}
) => Promise<number>
Parameters
An object with optional:
title: Modal title string.content: Modal content (ReactNode).onOk: Callback executed on confirmation, can be async.onCancel: Callback executed on cancel.
Returns
A function showDeleteConfirm which shows the modal and returns a Promise<number> that resolves or rejects based on user action.
Implementation Details
Uses Ant Design's
App.useApp()to access modal API.Uses
useTranslationfor localized strings.The confirmation dialog features a danger-styled OK button and a warning icon.
The promise resolves with the result of
onOkcallback or rejects ifonOkthrows.
Usage Example
const showDeleteConfirm = useShowDeleteConfirm();
const handleDelete = async () => {
try {
const result = await showDeleteConfirm({
content: "Are you sure to delete this item?",
onOk: async () => {
await deleteItem();
return 1;
},
});
console.log('Deleted:', result);
} catch {
console.log('Delete cancelled or failed');
}
};
5. useTranslate
Purpose
A convenience hook wrapping react-i18next's useTranslation hook scoped with a specific key prefix.
Signature
useTranslate(keyPrefix: string): UseTranslationResponse
Parameters
keyPrefix: The prefix string to scope translation keys.
Returns
The normal useTranslation hook object for the 'translation' namespace with the given prefix.
Usage Example
const { t } = useTranslate('dashboard');
return <h1>{t('welcomeMessage')}</h1>;
6. useCommonTranslation
Purpose
Provides a translation hook scoped to the 'common' key prefix, simplifying access to common UI strings.
Signature
useCommonTranslation(): UseTranslationResponse
Returns
The useTranslation hook object for the 'translation' namespace with 'common' key prefix.
Usage Example
const { t } = useCommonTranslation();
return <button>{t('submit')}</button>;
Important Implementation Details and Algorithms
Deep Comparison in
useDeepCompareEffect: Useslodash'sisEqualfor deep equality check instead of shallow comparison. This avoids unnecessary effect executions when dependencies are objects or arrays with equal content but different references.Dynamic SVG Importing:
useDynamicSVGImportleverages React's lazy loading and dynamicimport()to asynchronously load SVG components, improving initial load performance by deferring SVG loading until needed.Promise-based Modal Confirmation:
useShowDeleteConfirmwraps Ant Design modal confirmation dialogs into a Promise-based interface, enabling async/await patterns for cleaner async control flows in components.Translation Hooks: The translation hooks standardize the use of
react-i18nextwith consistent namespaces and key prefixes, reducing boilerplate around translation usage.
Interaction with Other System Parts
Ant Design (
antd): Uses Ant Design's Modal and Icon components for UI elements and modal dialogs.React-i18next: Integrates with
react-i18nextfor internationalization support.Lodash (
isEqual): Uses for deep comparison logic.SVG Assets: Dynamically imports SVG components from file paths or modules, requiring proper bundler support for SVG imports (e.g., webpack with
@svgr/webpack).Application Components: Hooks like
useSetModalState,useShowDeleteConfirm, and translation hooks are designed to be used inside React components to manage state, UI, and localization.
Visual Diagram
The following Mermaid flowchart illustrates the main hooks in this file and their key relationships or dependencies:
flowchart TD
A[useSetModalState] -->|Returns| B(visible, showModal, hideModal, switchVisible)
C[useDeepCompareEffect] -->|Uses| D[lodash isEqual]
E[useDynamicSVGImport] -->|Dynamically imports| F[SVG React Component]
E -->|Uses| G[useEffect]
H[useShowDeleteConfirm] -->|Uses| I[Ant Design Modal]
H -->|Uses| J[useTranslation]
K[useTranslate] -->|Wrapper| J
L[useCommonTranslation] -->|Wrapper| J
style A fill:#f9f,stroke:#333,stroke-width:1px
style C fill:#ccf,stroke:#333,stroke-width:1px
style E fill:#cfc,stroke:#333,stroke-width:1px
style H fill:#fcf,stroke:#333,stroke-width:1px
style K fill:#cff,stroke:#333,stroke-width:1px
style L fill:#cff,stroke:#333,stroke-width:1px
Summary
common-hooks.tsx encapsulates a variety of reusable React hooks focused on UI state management, asynchronous resource loading, modal dialogs, and localization. It leverages popular libraries such as Ant Design and react-i18next, and utility packages like lodash for robust implementation. These hooks enable developers to implement common patterns with less boilerplate, better abstraction, and improved maintainability.