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

Returns

An object containing:

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

Returns

Void.

Implementation Details

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

Returns

An object containing:

Implementation Details

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

Returns

A function showDeleteConfirm which shows the modal and returns a Promise<number> that resolves or rejects based on user action.

Implementation Details

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

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


Interaction with Other System Parts


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.