or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-operations.mddata-structures.mddom-interactions.mdeffects.mdindex.mdperformance.mdspecialized-hooks.mdstate-management.mdstorage.mdtimers.md
tile.json

index.mddocs/

ahooks

ahooks is a comprehensive collection of React hooks utilities providing 79+ high-quality hooks for modern React development. Built with TypeScript-first approach, it offers solutions for state management, side effects, performance optimization, DOM interactions, and much more. The library is designed to be tree-shakeable, SSR-compatible, and well-tested.

Package Information

  • Package Name: ahooks
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install ahooks
  • Repository: https://github.com/alibaba/hooks
  • Version: 3.9.5

Core Imports

// Import specific hooks (recommended for tree-shaking)
import { useBoolean, useToggle, useLocalStorageState } from 'ahooks';

// Import utilities
import { clearCache, configResponsive } from 'ahooks';

For CommonJS environments:

const { useBoolean, useToggle, useLocalStorageState } = require('ahooks');

Basic Usage

import React from 'react';
import { useBoolean, useLocalStorageState, useRequest } from 'ahooks';

function UserProfile() {
  // Boolean state management
  const [isEditing, { setTrue: startEdit, setFalse: cancelEdit, toggle }] = useBoolean(false);
  
  // Persistent storage state
  const [username, setUsername] = useLocalStorageState('username', {
    defaultValue: 'Anonymous'
  });
  
  // Async data fetching
  const { data: profile, loading, error } = useRequest(
    () => fetch(`/api/users/${username}`).then(res => res.json()),
    {
      refreshDeps: [username]
    }
  );

  return (
    <div>
      {isEditing ? (
        <input 
          value={username} 
          onChange={(e) => setUsername(e.target.value)}
        />
      ) : (
        <span onClick={startEdit}>{username}</span>
      )}
      {loading && <div>Loading...</div>}
      {profile && <div>{profile.bio}</div>}
    </div>
  );
}

Architecture

ahooks is organized into focused functional categories, each addressing specific development needs:

  • State Management: Enhanced state management with specialized hooks for booleans, counters, objects, and data structures
  • Effect System: Extended useEffect patterns including lifecycle, async, debounced, and deep comparison effects
  • Performance: Optimization hooks for memoization, preventing unnecessary re-renders, and managing references
  • DOM Integration: Comprehensive DOM interaction hooks for events, gestures, measurements, and viewport tracking
  • Async Operations: Powerful request management with caching, polling, and retry mechanisms
  • Storage Integration: Browser storage hooks with automatic serialization and synchronization
  • Timer Management: Declarative timers, intervals, and countdown functionality
  • Developer Tools: Debugging utilities and development helpers

The library uses a plugin architecture for extensibility (especially in useRequest) and maintains consistent patterns across all hooks for predictable behavior.

Capabilities

State Management

Enhanced state management hooks for common patterns beyond basic useState.

function useBoolean(defaultValue?: boolean): [boolean, Actions];
function useToggle<T = boolean>(): [boolean, Actions<T>];
function useCounter(initialValue?: number, options?: Options): [number, Actions];
function useSetState<T extends Record<string, any>>(
  initialState?: T | (() => T)
): [T, (patch: Partial<T> | ((prev: T) => Partial<T>)) => void];

State Management

Effects

Advanced effect hooks for lifecycle management, async operations, and performance optimization.

function useMount(fn: MountCallback): void;
function useUnmount(fn: () => void): void;
function useUpdateEffect(effect: EffectCallback, deps?: DependencyList): void;
function useAsyncEffect(
  effect: () => AsyncGenerator<void, void, void> | Promise<void>,
  deps?: DependencyList
): void;
function useDebounceEffect(
  effect: EffectCallback,
  deps?: DependencyList,
  options?: DebounceOptions
): void;

Effects

DOM Interactions

Comprehensive hooks for DOM events, measurements, and user interactions.

function useClickAway<T extends Event = Event>(
  onClickAway: (event: T) => void,
  target: BasicTarget | BasicTarget[],
  eventName?: DocumentEventKey | DocumentEventKey[]
): void;
function useEventListener<K extends keyof HTMLElementEventMap>(
  eventName: K,
  handler: (ev: HTMLElementEventMap[K]) => void,
  options?: Options<HTMLElement>
): void;
function useHover(target: BasicTarget, options?: Options): boolean;
function useSize(target: BasicTarget): Size | undefined;

DOM Interactions

Async Operations

Powerful async request management with comprehensive plugin system.

function useRequest<TData, TParams extends any[]>(
  service: Service<TData, TParams>,
  options?: Options<TData, TParams>
): Result<TData, TParams>;
function useLockFn<P extends any[] = any[], V = any>(
  fn: (...args: P) => Promise<V>
): (...args: P) => Promise<V | undefined>;

Async Operations

Storage

Browser storage integration with automatic serialization and state synchronization.

function useLocalStorageState<T>(
  key: string,
  options?: Options<T>
): [T | undefined, (value?: T | ((prev?: T) => T)) => void];
function useSessionStorageState<T>(
  key: string,
  options?: Options<T>
): [T | undefined, (value?: T | ((prev?: T) => T)) => void];
function useCookieState(cookieKey: string, options?: Options): [State, UpdateState];

Storage

Performance

Optimization hooks for preventing unnecessary re-renders and managing expensive computations.

function useMemoizedFn<T extends noop>(fn: T): T;
function useLatest<T>(value: T): MutableRefObject<T>;
function useCreation<T>(factory: () => T, deps: DependencyList): T;
function usePrevious<T>(state: T, shouldUpdate?: ShouldUpdateFunc<T>): T | undefined;

Performance

Timers

Declarative timer management with automatic cleanup and control.

function useInterval(
  fn: () => void,
  delay?: number,
  options?: { immediate?: boolean }
): () => void;
function useTimeout(fn: () => void, delay?: number): void;
function useCountDown(options?: Options): [number, FormattedRes];

Timers

Data Structures

Advanced data structure management with optimized operations.

function useMap<K, T>(initialValue?: Iterable<readonly [K, T]>): [Map<K, T>, MapActions<K, T>];
function useSet<K>(initialValue?: Iterable<K>): [Set<K>, SetActions<K>];
function useDynamicList<T>(initialList?: T[]): DynamicListActions<T>;
function useSelections<T>(items: T[], defaultSelected?: T[]): SelectionActions<T>;

Data Structures

Specialized Hooks

Specialized hooks for advanced use cases including tables, virtual lists, WebSocket, and developer tools.

function useAntdTable<TData extends Data, TParams extends Params>(
  service: Service<TData, TParams>,
  options?: AntdTableOptions<TData, TParams>
): AntdTableResult<TData, TParams>;
function useFusionTable<TData extends Data, TParams extends Params>(
  service: Service<TData, TParams>,
  options?: FusionTableOptions<TData, TParams>
): FusionTableResult<TData, TParams>;
function useVirtualList<T = any>(list: T[], options: Options<T>): VirtualListReturn<T>;
function useWebSocket(socketUrl: string, options?: Options): Result;

Specialized Hooks

Common Types

// Basic target for DOM operations
type BasicTarget<T = Element> = (() => T | null) | T | null | MutableRefObject<T>;

// Common callback types
type noop = (...args: any[]) => any;
type EffectCallback = () => void | (() => void);
type MountCallback = EffectCallback | (() => Promise<void | (() => void)>);

// Debounce/Throttle options
interface DebounceOptions {
  wait?: number;
  leading?: boolean;
  trailing?: boolean;
  maxWait?: number;
}

interface ThrottleOptions {
  wait?: number;
  leading?: boolean;
  trailing?: boolean;
}

// Storage serializer interface
interface Serializer<T> {
  read(value: string): T;
  write(value: T): string;
}

// Event types for DOM interactions
type DocumentEventKey = keyof DocumentEventMap;
type WindowEventKey = keyof WindowEventMap;

// Table management types
interface Data {
  list: any[];
  total: number;
}

type Params = [any, any]; // [pagination, formData]
type Service<TData extends Data, TParams extends Params> = (...args: TParams) => Promise<TData>;

// Fusion Table specific types
interface FusionTableOptions<TData extends Data, TParams extends Params> {
  field?: any; // Fusion Form field instance
  defaultType?: 'simple' | 'advance';
  defaultPageSize?: number;
  defaultParams?: TParams;
  manual?: boolean;
  refreshDeps?: any[];
  onSuccess?: (data: TData, params: TParams) => void;
  onError?: (error: Error, params: TParams) => void;
}

interface FusionTableResult<TData extends Data, TParams extends Params> {
  paginationProps: {
    onChange: (current: number) => void;
    onPageSizeChange: (size: number) => void;
    current: number;
    pageSize: number;
    total: number;
  };
  tableProps: {
    dataSource: TData['list'];
    loading: boolean;
    onSort: (dataIndex: string, order: string) => void;
    onFilter: (filterParams: any) => void;
  };
  search: {
    type: 'simple' | 'advance';
    changeType: () => void;
    submit: () => void;
    reset: () => void;
  };
  loading: boolean;
  data?: TData;
  error?: Error;
  params?: TParams;
  run: (...params: TParams) => void;
  runAsync: (...params: TParams) => Promise<TData>;
  refresh: () => void;
  refreshAsync: () => Promise<TData>;
  cancel: () => void;
  mutate: (data?: TData) => void;
}