### Install v2 and v3 Dependencies Simultaneously
Source: https://ahooks.js.org/guide/upgrade
Install both ahooks-v2 and ahooks packages to manage the transition between versions.
```bash
npm install ahooks-v2 --save
npm install ahooks --save
```
--------------------------------
### Install Renamed use-url-state Package
Source: https://ahooks.js.org/guide/upgrade
Install the standalone use-url-state package using its new name, @ahooks.js/use-url-state.
```bash
npm install @ahooks.js/use-url-state --save
```
--------------------------------
### Basic UseVirtualList Setup
Source: https://ahooks.js.org/~demos/usevirtuallist-demo1
Sets up a virtual list with a given data source and item height. Requires `useVirtualList` and `useState` hooks.
```javascript
import React, { useState } from 'react';
import { useVirtualList } from 'ahooks';
const initialData = Array.from({ length: 10000 }).map((_, index) => `Item ${index}`);
export default () => {
const [data, setData] = useState(initialData);
const { list, containerProps, wrapperProps, scrollTo } = useVirtualList(data, {
itemHeight: 50,
});
return (
{list.map((item, index) => (
{item}
))}
);
};
```
--------------------------------
### useUnmount Basic Usage
Source: https://ahooks.js.org/hooks/use-unmount
This example demonstrates the basic usage of the useUnmount hook. The provided function will be executed automatically when the component unmounts.
```javascript
import { useUnmount } from 'ahooks';
export default () => {
useUnmount(() => {
console.log('Component is unmounting!');
});
return
Hello World!
;
};
```
--------------------------------
### AddSet Example
Source: https://ahooks.js.org/~demos/usemap-demo1
Demonstrates adding a new key-value pair to a Map. This is useful for dynamic data manipulation.
```javascript
[
[
"msg",
"hello world"
],
[
123,
"number type"
]
]
```
--------------------------------
### Install ahooks with npm
Source: https://ahooks.js.org/
Install the ahooks library using npm. This is the primary method for adding ahooks to your React project.
```bash
$ npm install --save ahooks
```
--------------------------------
### Install ahooks with bun
Source: https://ahooks.js.org/
Install the ahooks library using bun. A fast JavaScript runtime and package manager for adding ahooks to your React project.
```bash
$ bun add ahooks
```
--------------------------------
### useHover API Example
Source: https://ahooks.js.org/hooks/use-hover
This snippet shows the basic API signature for the useHover hook, including the target element and optional configuration options for callbacks.
```javascript
const isHovering = useHover(
target,
{
onEnter,
onLeave,
onChange
}
);
```
--------------------------------
### SWR Example with Cache Key
Source: https://ahooks.js.org/hooks/use-request/cache
Demonstrates SWR behavior by returning cached data first and then re-fetching in the background when a cacheKey is set. Experience the effect by clicking the button.
```javascript
import React from 'react';
import { useRequest } from 'ahooks';
const getArticle = (id) => {
console.log('Fetching article', id);
return new Promise((resolve) => {
setTimeout(() => {
resolve({
id,
title: `Article ${id}`,
});
}, 1000);
});
};
const CacheSWR = () => {
const { data, loading } = useRequest(getArticle, {
cacheKey: 'article-swr',
});
if (loading) {
return
Loading...
;
}
return (
Article
{data?.title}
);
};
export default CacheSWR;
```
--------------------------------
### Install useUrlState Hook
Source: https://ahooks.js.org/hooks/use-url-state
Install the useUrlState hook using npm. Ensure you have react-router v5 or v6 installed in your project.
```bash
npm i @ahooks.js/use-url-state -S
```
--------------------------------
### Basic Infinite Scroll Setup
Source: https://ahooks.js.org/hooks/use-infinite-scroll
Initializes the infinite scroll hook with a service function. Destructures data, loading states, and the loadMore function for manual triggering.
```javascript
const { data, loading, loadingMore, loadMore } = useInfiniteScroll(service);
```
--------------------------------
### Install ahooks with yarn
Source: https://ahooks.js.org/
Install the ahooks library using yarn. An alternative package manager for adding ahooks to your React project.
```bash
$ yarn add ahooks
```
--------------------------------
### Install ahooks.js using npm, yarn, pnpm, or bun
Source: https://ahooks.js.org/guide
Install the ahooks.js library using your preferred package manager. This command adds the library as a dependency to your project.
```bash
$ npm install --save ahooks
# or
$ yarn add ahooks
# or
$ pnpm add ahooks
# or
$ bun add ahooks
```
--------------------------------
### Install ahooks with pnpm
Source: https://ahooks.js.org/
Install the ahooks library using pnpm. Another package manager option for integrating ahooks into your React project.
```bash
$ pnpm add ahooks
```
--------------------------------
### Custom Cache Implementation
Source: https://ahooks.js.org/hooks/use-request/cache
Allows customization of cache storage using `setCache` and `getCache` functions. This example shows how to integrate custom caching logic.
```javascript
import React from 'react';
import { useRequest } from 'ahooks';
// Mock localStorage for demonstration
const mockStorage = {};
const customGetCache = (cacheKey) => {
console.log('Custom getCache:', cacheKey);
const item = mockStorage[cacheKey];
if (!item) return undefined;
// Simulate cache expiration
if (Date.now() - item.time > 10000) { // 10 seconds expiration
delete mockStorage[cacheKey];
return undefined;
}
return item;
};
const customSetCache = (cacheKey, cachedData) => {
console.log('Custom setCache:', cacheKey, cachedData);
mockStorage[cacheKey] = {
...cachedData,
time: Date.now(),
};
};
const getInfo = () => {
console.log('Fetching info');
return new Promise((resolve) => {
setTimeout(() => {
resolve('Some fetched info');
}, 1000);
});
};
const CustomCache = () => {
const { data, loading } = useRequest(getInfo, {
cacheKey: 'custom-info',
getCache: customGetCache,
setCache: customSetCache,
// Note: cacheTime and clearCache are not used in custom cache mode
});
if (loading) {
return
Loading...
;
}
return (
Custom Cache Info
{data}
);
};
export default CustomCache;
```
--------------------------------
### useCallback Example
Source: https://ahooks.js.org/hooks/use-memoized-fn
Demonstrates how the function reference changes when the dependency 'state' updates using useCallback.
```typescript
import { useState, useCallback } from 'react';
const [state, setState] = useState('');
// When the state changes, the func reference will change
const func = useCallback(() => {
console.log(state);
}, [state]);
```
--------------------------------
### Observe Visible Area Ratio with useInViewport
Source: https://ahooks.js.org/hooks/use-in-viewport
This example shows how to observe the visible area ratio of an element. It utilizes the `options.threshold` parameter to trigger updates at specific visibility percentages, useful for scroll-based animations or progress indicators.
```javascript
import React from 'react';
import { useInViewport } from 'ahooks';
const Demo = () => {
const [inViewport, ratio] = useInViewport(document.getElementById('observer-dom'), {
threshold: [0.2, 0.8],
});
return (
scroll here
observer dom
inViewport: {inViewport ? 'visible' : 'hidden'}
ratio: {ratio}
);
};
export default Demo;
```
--------------------------------
### Basic Polling Setup
Source: https://ahooks.js.org/hooks/use-request/polling
Configure `pollingInterval` to enable polling. The service will be requested every specified milliseconds. Polling can be stopped with `cancel` and restarted with `run` or `runAsync`.
```javascript
const { data, run, cancel } = useRequest(getUsername, {
pollingInterval: 3000,
});
```
--------------------------------
### Basic Responsive Info
Source: https://ahooks.js.org/hooks/use-responsive
Demonstrates how to use the useResponsive hook to get current responsive information. Change the browser window width to observe the changes.
```jsx
import React from 'react';
import { useResponsive } from 'ahooks';
export default () => {
const responsive = useResponsive();
return (
);
};
```
--------------------------------
### Support Shadow DOM with useClickAway
Source: https://ahooks.js.org/hooks/use-click-away
This example illustrates how to use useClickAway with elements within a Shadow DOM. It shows how to attach event listeners to the shadow root.
```typescript
import React, { useRef, useState, useEffect } from 'react';
import { useClickAway } from 'ahooks';
const ShadowDOMUseClickAway: React.FC = () => {
const [count, setCount] = useState(0);
const shadowHostRef = useRef(null);
const [shadowRoot, setShadowRoot] = useState(null);
useEffect(() => {
if (shadowHostRef.current && shadowHostRef.current.attachShadow) {
const root = shadowHostRef.current.attachShadow({ mode: 'open' });
setShadowRoot(root);
}
}, []);
useClickAway(() => {
setCount(count + 1);
}, shadowRoot as any);
return (
Shadow Host
Clicked outside shadow DOM: {count} times
);
};
export default ShadowDOMUseClickAway;
```
--------------------------------
### useScroll API Example
Source: https://ahooks.js.org/hooks/use-scroll
This shows the basic API signature for the useScroll hook, illustrating how to pass a target element and an optional update condition.
```javascript
const position = useScroll(target, shouldUpdate);
```
--------------------------------
### Basic Loading Delay Example
Source: https://ahooks.js.org/hooks/use-request/loading-delay
This snippet demonstrates how to use `loadingDelay` to prevent the UI from showing 'Loading...' if the request completes within the specified delay. Set `loadingDelay` to 300ms.
```javascript
const { loading, data } = useRequest(getUsername, {
loadingDelay: 300
});
return
{ loading ? 'Loading...' : data }
```
--------------------------------
### useUnmount Hook Implementation
Source: https://ahooks.js.org/guide/blog/function
An example of a custom Hook (useUnmount) that utilizes useRef to manage the latest callback function, ensuring it's correctly executed on unmount.
```javascript
const useUnmount = (fn) => {
const fnRef = useRef(fn);
fnRef.current = fn;
useEffect(
() => () => {
fnRef.current();
},
[],
);
};
```
--------------------------------
### Listening for Other Events with useClickAway
Source: https://ahooks.js.org/hooks/use-click-away
This example shows how to configure useClickAway to listen for events other than the default 'click'. Here, it's set up to listen for 'contextmenu' events.
```typescript
import React, { useRef, useState } from 'react';
import { useClickAway } from 'ahooks';
const ListenOtherEventsUseClickAway: React.FC = () => {
const [count, setCount] = useState(0);
const nodeRef = useRef(null);
useClickAway(() => {
setCount(count + 1);
}, nodeRef, 'contextmenu');
return (
Context menu outside: {count} times
);
};
export default ListenOtherEventsUseClickAway;
```
--------------------------------
### Advanced useInterval Usage with Dynamic Interval and Control
Source: https://ahooks.js.org/hooks/use-interval
This example shows advanced usage of useInterval, allowing the interval delay to be changed dynamically and providing controls to pause and resume the interval. It's useful for timers that need to adapt to different conditions or user interactions.
```javascript
import React, { useState, useCallback } from 'react';
import { useInterval } from 'ahooks';
export default () => {
const [count, setCount] = useState(0);
const [delay, setDelay] = useState(1000);
const [isRunning, setIsRunning] = useState(true);
const increment = useCallback(() => setCount((c) => c + 1), []);
useInterval(increment, isRunning ? delay : null);
const handleReset = () => {
setCount(0);
};
const handlePause = () => {
setIsRunning(false);
};
const handleResume = () => {
setIsRunning(true);
};
const handleIntervalChange = (e) => {
setDelay(Number(e.target.value));
};
return (
Count: {count}
);
};
```
--------------------------------
### useDebounceFn Default Usage
Source: https://ahooks.js.org/hooks/use-debounce-fn
This example demonstrates the default usage of useDebounceFn. The debounced function will execute 500ms after the last invocation, useful for handling frequent events like button clicks.
```javascript
import { useDebounceFn } from 'ahooks';
import { useState } from 'react';
export default () => {
const [count, setCount] = useState(0);
const debounceFn = useDebounceFn(() => {
setCount(count + 1);
}, {
wait: 500,
});
return (
Clicked count: {count}
);
};
```
--------------------------------
### usePrevious with Custom shouldUpdate Function
Source: https://ahooks.js.org/hooks/use-previous
This example shows how to use the `shouldUpdate` function with `usePrevious` to conditionally update the previous state. The previous value only changes when the provided function returns true.
```jsx
import React, { useState, useCallback } from 'react';
import { usePrevious } from 'ahooks';
interface User {
name: string;
job: string;
}
const INITIAL_USER: User = {
name: 'Jack',
job: 'student',
};
export default () => {
const [user, setUser] = useState(INITIAL_USER);
const prevUser = usePrevious(user, (prev, next) => {
// Update previous value only when job changes
return prev?.job !== next.job;
});
const updateUser = useCallback(() => {
setUser(preUser => ({
...preUser,
job: preUser.job === 'student' ? 'teacher' : 'student',
}));
}, []);
return (
Current name: {user.name}
Current job: {user.job}
Previous name: {prevUser?.name}
Previous job: {prevUser?.job}
);
};
```
--------------------------------
### Second-based Countdown
Source: https://ahooks.js.org/hooks/use-count-down
Provides a method to get a countdown accurate to the second by rounding the millisecond value. This can be useful to mitigate potential precision issues around the start of the countdown.
```javascript
const [countdown] = useCountDown(targetDate);
const seconds = Math.round(countdown / 1000);
```
--------------------------------
### Clone and set up ahooks repository
Source: https://ahooks.js.org/
Clone the ahooks GitHub repository and set up the development environment. This is for contributors who want to work on the library itself.
```bash
$ git clone git@github.com:alibaba/hooks.git
$ cd hooks
$ pnpm run init
$ pnpm start
```
--------------------------------
### Get EventEmitter Instance
Source: https://ahooks.js.org/hooks/use-event-emitter
Call useEventEmitter in your React component to get an instance of EventEmitter. This instance remains unchanged across re-renders.
```javascript
const event$ = useEventEmitter();
```
--------------------------------
### Basic Usage of useDynamicList
Source: https://ahooks.js.org/hooks/use-dynamic-list
Demonstrates the fundamental usage of useDynamicList for managing a list of items, including adding and removing elements.
```javascript
import React from 'react';
import { useDynamicList } from 'ahooks';
const InitialList = () => {
const { list, push, remove, getKey } = useDynamicList(['David', 'Jack']);
return (
{list.map((item, index) => (
{item}
))}
);
};
export default InitialList;
```
--------------------------------
### Get Current Document Visibility
Source: https://ahooks.js.org/hooks/use-document-visibility
This snippet shows how to get the current visibility state of the document using the useDocumentVisibility hook. It's useful for initializing state based on whether the page is already visible when the component mounts.
```javascript
const documentVisibility = useDocumentVisibility();
```
--------------------------------
### Configure Custom Breakpoints
Source: https://ahooks.js.org/hooks/use-responsive
Shows how to configure custom responsive breakpoints using the configResponsive function. This should only be called once.
```javascript
import { configResponsive } from 'ahooks';
configResponsive({
small: 0,
middle: 800,
large: 1200,
});
```
--------------------------------
### useScroll API
Source: https://ahooks.js.org/hooks/use-scroll
Get the scroll position of an element. It accepts a target element and an optional update condition.
```APIDOC
## useScroll
Get the scroll position of an element.
### API
```javascript
const position = useScroll(target, shouldUpdate);
```
### Params
#### `target`
* **Description**: DOM element or ref object
* **Type**: `Element` | `(() => Element)` | `MutableRefObject`
* **Default**: `document`
#### `shouldUpdate`
* **Description**: Whether to update position. This function receives the current scroll position and should return a boolean indicating whether to update.
* **Type**: `({ top: number, left: number }) => boolean`
* **Default**: `() => true`
### Result
The `position` object contains the current scroll position with `top` and `left` properties.
```
--------------------------------
### useRequest Ready in Manual Mode
Source: https://ahooks.js.org/hooks/use-request/ready
Illustrates 'ready' behavior in manual mode. Requests triggered by 'run' will only execute if 'ready' is true.
```javascript
import React, { useState } from 'react';
import { useRequest } from 'ahooks';
interface User {
username: string;
}
const getUser = async (id: string): Promise => {
console.log(id);
await new Promise((resolve) => setTimeout(resolve, 1000));
return {
username: 'ahooks',
};
};
export default () => {
const [ready, setReady] = useState(false);
const { data, loading, run } = useRequest(getUser, {
manual: true,
ready,
defaultParams: ['123'],
});
return (
Ready: {JSON.stringify(ready)}
Username: {data?.username}
{loading &&
Loading...
}
);
};
```
--------------------------------
### Default Usage of useMap
Source: https://ahooks.js.org/hooks/use-map
Demonstrates the basic usage of the useMap hook to add, remove, and reset entries in a Map. It shows how to initialize the map with key-value pairs and how the map state is represented.
```javascript
const [map, { set, remove, reset }] = useMap([
['msg', 'hello world'],
[123, 'number type'],
]);
// Example operations:
set('newKey', 'newValue');
remove('msg');
reset();
```
--------------------------------
### Default Usage of useFullscreen
Source: https://ahooks.js.org/hooks/use-fullscreen
Demonstrates the basic usage of the useFullscreen hook. It shows how to obtain the full-screen state and control functions, and how to apply them to a target element.
```javascript
const [isFullscreen, { enterFullscreen, exitFullscreen, toggleFullscreen }] = useFullScreen();
```
--------------------------------
### useMemoizedFn Example
Source: https://ahooks.js.org/hooks/use-memoized-fn
Shows how useMemoizedFn ensures a stable function reference, even when 'state' changes, by omitting the dependency array.
```typescript
import { useState } from 'react';
import { useMemoizedFn } from 'ahooks';
const [state, setState] = useState('');
// func reference never change
const func = useMemoizedFn(() => {
console.log(state);
});
```
--------------------------------
### Basic Usage of useKeyPress
Source: https://ahooks.js.org/hooks/use-key-press
Demonstrates listening for ArrowUp and ArrowDown keys to control a counter. Supports both keyCode and alias for key identification.
```jsx
import React from 'react';
import { useKeyPress } from 'ahooks';
export default () => {
const [count, setCount] = React.useState(0);
useKeyPress('ArrowUp', () => {
setCount((c) => c + 1);
});
useKeyPress(38, () => {
setCount((c) => c - 1);
});
return (
Counter: {count}
);
};
```
--------------------------------
### Custom useRequest with Data Formatting
Source: https://ahooks.js.org/guide/upgrade
When options.formatResult is deleted, format the service to return data in the final format. This example shows how to extract result.data.
```javascript
const { data } = useRequest(async () => {
const result = await getData();
return result.data;
});
```
--------------------------------
### Default Usage of useSet
Source: https://ahooks.js.org/hooks/use-set
Demonstrates the basic usage of the useSet hook, including adding and removing elements from a Set.
```javascript
import { useSet } from 'ahooks';
const Demo = () => {
const [set, { add, remove, reset }] = useSet(['Hello']);
return (
Current Set: {JSON.stringify(Array.from(set.values()))}
);
};
export default Demo;
```
--------------------------------
### useRequest Ready in Automatic Mode
Source: https://ahooks.js.org/hooks/use-request/ready
Demonstrates how 'ready' controls request execution in automatic mode. A request is sent each time 'ready' transitions from false to true.
```javascript
import React, { useState } from 'react';
import { useRequest } from 'ahooks';
interface User {
username: string;
}
const getUser = async (id: string): Promise => {
console.log(id);
await new Promise((resolve) => setTimeout(resolve, 1000));
return {
username: 'ahooks',
};
};
export default () => {
const [ready, setReady] = useState(false);
const { data, loading } = useRequest(getUser, {
ready,
defaultParams: ['123'],
});
return (
Ready: {JSON.stringify(ready)}
Username: {data?.username}
{loading &&
Loading...
}
);
};
```
--------------------------------
### useCreation vs useRef for Instantiation
Source: https://ahooks.js.org/hooks/use-creation
Demonstrates how useCreation ensures a value is instantiated only once, unlike useRef which can create new instances on every render. This is useful for creating stable objects like Subjects.
```typescript
import { useRef } from 'react';
import { useCreation } from 'ahooks';
// Assume Subject is a class that needs to be instantiated
class Subject {}
// Example usage within a component:
const a = useRef(new Subject()); // A new Subject instance is created in every render.
const b = useCreation(() => new Subject(), []); // By using factory function, Subject is only instantiated once.
```
--------------------------------
### Get Trigger Key with useKeyPress
Source: https://ahooks.js.org/hooks/use-key-press
Illustrates registering multiple shortcuts with different handlers. The hook can identify which specific key combination triggered the event.
```jsx
import React from 'react';
import { useKeyPress } from 'ahooks';
export default () => {
const [count, setCount] = React.useState(0);
useKeyPress('w', () => {
setCount((c) => c + 1);
});
useKeyPress('s', () => {
setCount((c) => c - 1);
});
useKeyPress('shift.c', () => {
setCount(0);
});
return (
Counter: {count}
);
};
```
--------------------------------
### useGetState API
Source: https://ahooks.js.org/hooks/use-get-state
The useGetState hook returns an array containing the current state, a function to update the state, and a function to get the latest state value.
```APIDOC
## useGetState
### Description
Provides a getter method to access the latest value returned by `React.useState`.
### Method Signature
```typescript
function useGetState(initialState: S | (() => S)): [S, Dispatch>, GetStateAction];
function useGetState(): [S | undefined, Dispatch>, GetStateAction];
```
### Parameters
- `initialState` (S | (() => S)): The initial state value or a function that returns the initial state.
### Returns
- `state` (S): The current state value.
- `setState` (Dispatch>): A function to update the state.
- `getState` (GetStateAction): A function that returns the latest state value.
### Example Usage
```javascript
const [state, setState, getState] = useGetState(0);
// To get the latest state value, use the getState function:
const latestState = getState();
```
```
--------------------------------
### Default Usage of useWebSocket
Source: https://ahooks.js.org/hooks/use-web-socket
Demonstrates the basic integration of the useWebSocket hook. It shows how to connect, send messages, disconnect, and monitor the connection status and received messages.
```typescript
import { useWebSocket } from 'ahooks';
const socketUrl = 'ws://example.com/ws';
const {
latestMessage,
sendMessage,
disconnect,
connect,
readyState,
} = useWebSocket(socketUrl);
// Example usage within a React component:
//
//
Ready State: {readyState}
//
Latest Message: {latestMessage?.data}
//
//
```
--------------------------------
### Clear Cache by Cache Key
Source: https://ahooks.js.org/hooks/use-request/cache
Provides a `clearCache` method to clear cached data for a specific `cacheKey`. Examples show clearing individual or all caches.
```javascript
import React from 'react';
import { useRequest, clearCache } from 'ahooks';
const getArticle = (id) => {
console.log('Fetching article', id);
return new Promise((resolve) => {
setTimeout(() => {
resolve({
id,
title: `Article ${id}`,
});
}, 1000);
});
};
const ArticleDisplay = ({ id }) => {
const { data, loading } = useRequest(getArticle, {
cacheKey: `article-${id}`,
});
if (loading) {
return
Loading...
;
}
return (
Article {id}
{data?.title}
);
};
const ClearCache = () => {
return (
);
};
export default ClearCache;
```
--------------------------------
### useKeyPress API Documentation
Source: https://ahooks.js.org/hooks/use-key-press
This section details the API for the useKeyPress hook, including its parameters, options, and remarks.
```APIDOC
## useKeyPress
Listen for the keyboard press, support key combinations, and support alias.
### API
```typescript
type KeyType = number | string;
type KeyFilter = KeyType | KeyType[] | ((event: KeyboardEvent) => boolean);
useKeyPress(
keyFilter: KeyFilter,
eventHandler: (event: KeyboardEvent, key: KeyType) => void,
options?: Options
);
```
### Params
| Property | Description | Type | Default |
|---|---|---|---|
| keyFilter | Support keyCode, alias, combination keys, array, custom function | `KeyType` | `KeyType[]` | `(event: KeyboardEvent) => boolean` | - |
| eventHandler | Callback function | `(event: KeyboardEvent, key: KeyType) => void` | - |
| options | Advanced options | `Options` | - |
### Options
| Property | Description | Type | Default |
|---|---|---|---|
| events | Trigger Events | `('keydown' | 'keyup')[]` | `['keydown']` |
| target | DOM element or ref | `() => Element` | `Element` | `MutableRefObject` | - |
| exactMatch | Exact match. If set `true`, the event will only be trigger when the keys match exactly. For example, pressing [shift + c] will not trigger [c] | `boolean` | `false` |
| useCapture | to block events bubbling | `boolean` | `false` |
### Remarks
1. Supports part of standard browser key values. Reference: MDN keyboard key values. Full alias list refers to code
2. Modifier keys:
```
ctrl
alt
shift
meta
```
```
--------------------------------
### useGetState Hook API Usage
Source: https://ahooks.js.org/hooks/use-get-state
Illustrates the basic usage pattern of the useGetState hook, showing how to destructure the state, setState, and getState functions from its return value.
```javascript
const [state, setState, getState] = useGetState(initialState)
```
--------------------------------
### Direct DOM Access in Hook (Problematic)
Source: https://ahooks.js.org/guide/blog/ssr
This example shows a common mistake where a hook directly accesses `document.visibilityState` during initial render, which fails in SSR.
```jsx
import React, { useState } from 'react';
export default () => {
const [state, setState] = useState(document.visibilityState);
return state;
};
```
--------------------------------
### Basic Polling Configuration
Source: https://ahooks.js.org/hooks/use-request/polling
Demonstrates how to enable polling by setting the `pollingInterval` option. The service will be executed every specified milliseconds. Polling can be stopped with `cancel` and restarted with `run` or `runAsync`.
```APIDOC
## Basic Polling
By setting `options.pollingInterval`, enter polling mode, `useRequest` will periodically trigger service execution.
```javascript
const { data, run, cancel } = useRequest(getUsername, {
pollingInterval: 3000,
});
```
In the above scenario, `getUsername` will be requested every 3000ms. You can stop polling by `cancel` and start polling by `run/runAsync`.
```
--------------------------------
### useCounter Basic Usage
Source: https://ahooks.js.org/hooks/use-counter
Demonstrates the basic usage of the useCounter hook for managing a counter. It shows how to initialize the counter and use the provided functions to modify its value.
```javascript
const [current, {
inc,
dec,
set,
reset
}] = useCounter(initialValue, { min, max });
```
--------------------------------
### Multiple Keys with useKeyPress
Source: https://ahooks.js.org/hooks/use-key-press
Shows how to register multiple distinct keys or key ranges for different actions. Supports individual keys, ranges, and combinations.
```jsx
import React from 'react';
import { useKeyPress } from 'ahooks';
export default () => {
const [state, setState] = React.useState([])
useKeyPress(/[0-9]/, () => {
setState((s) => [...s, 'number key'])
})
useKeyPress(['a', 's', 'd', 'f', 'Backspace', '8'], () => {
setState((s) => [...s, 'specific key'])
})
return (
Pressed keys:
{state.map((key) => (
{key}
))}
);
};
```
--------------------------------
### Data Freshness with staleTime
Source: https://ahooks.js.org/hooks/use-request/cache
Specifies data retention time using staleTime, preventing re-requests within this period. The example sets a fresh time of 5 seconds.
```javascript
import React from 'react';
import { useRequest } from 'ahooks';
const getTimestamp = () => {
console.log('Fetching timestamp');
return new Promise((resolve) => {
setTimeout(() => {
resolve(Date.now());
}, 1000);
});
};
const FreshTime = () => {
const { data, loading } = useRequest(getTimestamp, {
staleTime: 5000, // 5 seconds
});
if (loading) {
return
Loading...
;
}
return (
Timestamp
{data}
);
};
export default FreshTime;
```
--------------------------------
### useDebounce API Documentation
Source: https://ahooks.js.org/hooks/use-debounce
This section details the API for the useDebounce hook, including its parameters and options for configuring debounce behavior.
```APIDOC
## useDebounce
A hook that deals with the debounced value.
### API
```javascript
const debouncedValue = useDebounce(
value: any,
options?: Options
);
```
### Params
| Property | Description | Type | Default |
|---|---|---|---|
| value | The value to debounce. | `any` | - |
| options | Config for the debounce behaviors. | `Options` | - |
### Options
| Property | Description | Type | Default |
|---|---|---|---|
| wait | The number of milliseconds to delay. | `number` | `1000` |
| leading | Specify invoking on the leading edge of the timeout. | `boolean` | `false` |
| trailing | Specify invoking on the trailing edge of the timeout. | `boolean` | `true` |
| maxWait | The maximum time func is allowed to be delayed before it’s invoked. | `number` | - |
```
--------------------------------
### Form Validation with useAntdTable
Source: https://ahooks.js.org/hooks/use-antd-table
useAntdTable automatically calls form.validateFields before submission. If validation fails, the request is not initiated, ensuring data integrity. This example demonstrates the validation process.
```jsx
male
name| email| phone| gender
---|---|---|---
No data
Current Table:
"root":{}
0 items
Current Form:
"root":{}
0 items
```
--------------------------------
### Custom DOM Target with useClickAway
Source: https://ahooks.js.org/hooks/use-click-away
This example shows how to use useClickAway with a custom DOM element or a function that returns a DOM element. It allows more flexibility in defining the target.
```typescript
import React, { useRef, useState } from 'react';
import { useClickAway } from 'ahooks';
const CustomDOMUseClickAway: React.FC = () => {
const [count, setCount] = useState(0);
const boxRef = useRef(null);
useClickAway(() => {
setCount(count + 1);
}, boxRef);
return (
Click me or outside this box
Clicked outside: {count} times
);
};
export default CustomDOMUseClickAway;
```
--------------------------------
### Basic Usage of useScroll
Source: https://ahooks.js.org/hooks/use-scroll
This snippet demonstrates the basic usage of the useScroll hook to get the scroll position of an element. It's useful for tracking scroll within specific components.
```javascript
import { useScroll } from 'ahooks';
import React, { useRef } from 'react';
export default () => {
const nodeRef = useRef(null);
const { top, left } = useScroll(nodeRef);
return (
Scroll me
top: {top}
left: {left}
);
};
```
--------------------------------
### Parameter Cache Initialization
Source: https://ahooks.js.org/hooks/use-request/cache
Utilizes the params caching mechanism to remember the last request's conditions and initialize with them next time. This example initializes the keyword from cached params.
```javascript
import React, { useState } from 'react';
import { useRequest } from 'ahooks';
const search = (params) => {
console.log('Searching with params:', params);
return new Promise((resolve) => {
setTimeout(() => {
resolve({
result: [
`Result for ${params.keyword}`,
`Another result for ${params.keyword}`,
],
params,
});
}, 1000);
});
};
const ParamCache = () => {
const [keyword, setKeyword] = useState('');
const { data, loading, params } = useRequest(
(p) => search(p),
{
cacheKey: 'search-params',
ready: !!keyword,
// Initial params will be fetched from cache if available
// If not, it will use the initial value provided here
initialData: { result: [], params: { keyword: '' } },
}
);
const handleSearch = () => {
// Trigger search with the current keyword
// If keyword is same as cached params.keyword, it will use cached data
// Otherwise, it will fetch new data
search({ keyword });
};
return (
);
};
export default ParamCache;
```
--------------------------------
### Toggle Between Any Two Values with useToggle
Source: https://ahooks.js.org/hooks/use-toggle
Shows how to use useToggle to toggle between any two specified values, not just booleans. This is useful for cycling through custom states.
```javascript
import { useToggle } from 'ahooks';
const Component = () => {
const [state, { toggle, set, setLeft, setRight }] = useToggle('Hello', 'World');
return (
State: {state}
);
};
```
--------------------------------
### useTheme Hook API
Source: https://ahooks.js.org/hooks/use-theme
This hook is used to get and set the theme, and store the `themeMode` into `localStorage`. It returns the current theme, the selected theme mode, and a function to update the theme mode.
```APIDOC
## useTheme
### Description
This hook is used to get and set the theme, and store the `themeMode` into `localStorage`.
### API
```javascript
const { theme, themeMode, setThemeMode } = useTheme({
localStorageKey?: string;
});
```
### Params
#### localStorageKey
- **localStorageKey** (string) - Optional - The key in localStorage to store selected theme mode. Defaults to `undefined`.
### Result
#### theme
- **theme** (string) - Description: current display theme. Possible values: "light" or "dark". If `themeMode` is "system", it equals to system setting, otherwise it equals to `themeMode`. Default: depends on `themeMode`.
#### themeMode
- **themeMode** (string) - Description: selected theme mode. Possible values: "light", "dark", or "system". Defaults to localStorage value for "themeMode", otherwise "system".
#### setThemeMode
- **setThemeMode** (function) - Description: select theme mode. Accepts a mode of type "light", "dark", or "system". Signature: `(mode: "light" | "dark" | "system") => void`.
```
--------------------------------
### Detecting Whole Page Scroll
Source: https://ahooks.js.org/hooks/use-scroll
This example shows how to use useScroll to detect scroll events on the entire document. It's suitable for implementing features that react to global page scrolling.
```javascript
import { useScroll } from 'ahooks';
import React from 'react';
export default () => {
const { top, left } = useScroll(document);
return (
Whole page scroll:
top: {top}
left: {left}
Scroll down to see the values change.
);
};
```
--------------------------------
### Listening for Keydown Events with useEventListener
Source: https://ahooks.js.org/hooks/use-event-listener
Shows how to use useEventListener to listen for keydown events on the document. This is useful for capturing keyboard input globally.
```jsx
import React from 'react';
import { useEventListener } from 'ahooks';
export default () => {
const [key, setKey] = React.useState('');
useEventListener(
'keydown',
(event: any) => {
setKey(event.key);
},
);
return
Your press key is {key}
;
};
```
--------------------------------
### Example of HMR Issue with useRequest
Source: https://ahooks.js.org/guide/blog/hmr
This code demonstrates a scenario where the `loading` state in a `useRequest` hook remains true after HMR due to the `isUnmount` ref incorrectly indicating an unmounted component.
```javascript
import React, { useEffect, useState } from 'react';
function getUsername() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('test');
}, 1000);
});
}
export default function IndexPage() {
const isUnmount = React.useRef(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
getUsername().then(() => {
if (isUnmount.current === false) {
setLoading(false);
}
});
return () => {
isUnmount.current = true;
};
}, []);
return loading ?
loading
:
hello world
;
}
```
--------------------------------
### useCreation API
Source: https://ahooks.js.org/hooks/use-creation
The useCreation hook takes a factory function and a dependency array to create and memoize a value. The factory function is only called once.
```APIDOC
## useCreation(factory: () => T, deps: any[]): T
### Description
Creates a value using a factory function that is guaranteed to be called only once. This hook serves as a more reliable alternative to `useMemo` for performance optimizations and can be used like `useRef` to create persistent values across renders.
### Parameters
#### Factory Function (`factory`)
- **Type**: `() => T`
- **Description**: A function that returns the value to be created and memoized. This function is executed only on the initial render.
#### Dependency List (`deps`)
- **Type**: `any[]`
- **Description**: A list of dependencies. If any dependency changes, the factory function will be re-executed. However, `useCreation` is primarily designed to ensure the factory is called only once, making this dependency list less critical for its core guarantee compared to `useMemo`.
```
--------------------------------
### Basic Usage of useToggle
Source: https://ahooks.js.org/hooks/use-toggle
Demonstrates the basic usage of useToggle, which defaults to boolean toggling similar to useBoolean. Use this when you need a simple boolean toggle.
```javascript
import { useToggle } from 'ahooks';
const Component = () => {
const [state, { toggle, setLeft, setRight }] = useToggle();
return (