### Install @shined/react-use Library
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/get-started.mdx
Instructions for installing the `@shined/react-use` library using various JavaScript package managers.
```npm
npm install @shined/react-use
```
```yarn
yarn add @shined/react-use
```
```pnpm
pnpm add @shined/react-use
```
```bun
bun add @shined/react-use
```
--------------------------------
### Run Next.js Development Server
Source: https://github.com/sheinsight/react-use/blob/main/examples/nextjs-ssr/readme.md
Commands to start the local development server for a Next.js application, enabling live preview and auto-updates in the browser.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
--------------------------------
### Example Usage of useAsyncFn Hook in React
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/get-started.mdx
Demonstrates how to use the `useAsyncFn` Hook to handle asynchronous operations like data fetching, managing loading states and errors within a React component.
```tsx
function App() {
const { loading, error, run } = useAsyncFn(fetchData)
return (
<>
{data}
>
)
}
```
--------------------------------
### useTimeout Hook Basic Usage Examples
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-timeout/index.zh-cn.mdx
Demonstrates the basic usage of the `useTimeout` hook, showing how to get a simple boolean timeout status or access more control functions like `start`, `pause`, and `reset`.
```tsx
const isTimeout = useTimeout(2000)
const { isTimeout, start, pause, reset } = useTimeout(2000, { controls: true })
```
--------------------------------
### Examples of useQuery Fetcher Functions
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.mdx
This snippet demonstrates various implementations of the `Fetcher` function, which is an asynchronous function that returns a Promise for data fetching. Examples include native `fetch`, Axios, GraphQL, and custom Promise-based functions, illustrating its independence from specific request libraries and its ability to handle errors.
```tsx
// Native Fetch request
const fetchData = async () => await (await fetch('https://api.example.com/data').json())
// Axios request
const fetchData = () => axios.get('https://api.example.com/data').then(res => res.data)
// GraphQL request
const fetchData = () => graphqlClient.query({ query: gql`{ data }` }).then(res => res.data)
// Custom Promise function
const fetchData = () => new Promise(resolve => setTimeout(() => resolve('data'), 1000))
// Can throw errors
const fetchData = () => new Promise((_, reject) => setTimeout(() => reject('error'), 1000))
```
--------------------------------
### Initialize createSingleLoading Utility
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/create-single-loading/index.mdx
Demonstrates how to import `create` from `@shined/reactive` and initialize `createSingleLoading` to obtain its core functions for managing loading state, including `set`, `get`, `bind`, `useLoading`, and `useAsyncFn`.
```tsx
import { create } from '@shined/reactive';
const pageLoading = createSingleLoading({ create });
const { set, get, bind, useLoding, useAsyncFn } = pageLoading;
```
--------------------------------
### React Hook useInputComposition Usage Example
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-input-composition/index.mdx
Illustrates the basic destructuring of the `useInputComposition` hook's return values, showing how to access `isComposing` and `data`.
```tsx
const { isComposiing, data } = useInputComposition(elementTarget)
```
--------------------------------
### useResizeObserver Hook Options Interface Definition
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-resize-observer/index.mdx
Defines the `UseResizeObserverOptions` interface, detailing parameters like `immediate` (to start observation immediately) and `box` (specifying the observed box model).
```APIDOC
export interface UseWebObserverOptions {
/**
* Start the observer immediate after calling this function
*
* @defaultValue true
*/
immediate?: boolean
}
interface ResizeObserverOptions {
box?: ResizeObserverBoxOptions
}
export interface UseResizeObserverOptions extends UseWebObserverOptions, ResizeObserverOptions {
/** @defaultValue 'content-box' */
box?: ResizeObserverBoxOptions
}
```
--------------------------------
### useReportingObserver API: Options
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-reporting-observer/index.mdx
Defines the configuration options available for the `useReportingObserver` hook, including whether to start immediately and standard `ReportingObserverOptions` like `buffered` and `types`.
```APIDOC
export type UseWebObserverOptions = {
/**
* Start the observer immediate after calling this function
*
* @defaultValue true
*/
immediate?: boolean
}
interface ReportingObserverOptions {
buffered?: boolean
types?: string[]
}
export interface UseReportingObserverOptions extends UseWebObserverOptions, ReportingObserverOptions {}
```
--------------------------------
### Manage Data Fetching with useQuery Hook
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/usage-guide.mdx
This section demonstrates two approaches to data fetching in React. It contrasts the manual state management using `useState` and `useEffect` with the more semantic and automated approach provided by the `useQuery` hook, which simplifies state handling and offers control operations like `run`, `cancel`, and `refresh`.
```tsx
// Not recommended
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const [data, setData] = useState(null)
useEffect(() => {
setLoading(true)
fetch('https://api.example.com/data')
.then((res) => res.json())
.then((data) => {
setData(data)
setLoading(false)
})
.catch((error) => {
setError(error)
setLoading(false)
})
}, [])
```
```tsx
// Recommended
const fetcher = () => fetch('https://api.example.com/data').then((res) => res.json())
const { loading, error, data, run, cancel, refresh } = useQuery(fetcher, {
refreshInterval: 1000
});
// The data fetching can be controlled by operations such as run, cancel, and refresh
run()
```
--------------------------------
### Basic Usage of useCounter Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-counter/index.zh-cn.mdx
Demonstrates how to initialize and interact with the `useCounter` hook, including incrementing, decrementing, setting, resetting, and getting the counter value.
```tsx
const [count, actions] = useCounter(20)
const [count, actions, couterState] = useCounter(20, { min: 1, max: 100 })
// 增加计数器
actions.inc()
actions.inc(2)
// 减少计数器
actions.dec()
actions.dec(4)
// 设置计数器为指定值
actions.set(10)
// 重置计数器为初始值(或同时重设初始值)
actions.reset()
actions.reset(12)
// 获取计数器的值,值为 count
acitons.get()
```
--------------------------------
### React useForm Hook Basic Usage and Destructuring
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-form/index.mdx
Demonstrates how to destructure properties from the `useForm` hook and provides a basic example of its initialization with `initialValues` and `onSubmit`.
```tsx
const {
value,
setValue,
setFieldValue,
submit,
reset,
submitting,
initialValue,
handleChange,
handleSubmit,
handleReset,
checkValidity,
reportValidity,
nativeProps,
} = useForm(options)
// Example usage
const form = useForm({
initialValues: {
name: 'John Doe',
email: 'hi@john.doe',
},
onSubmit: (form) => {
console.log(form)
},
})
```
--------------------------------
### Handle Data Pagination with usePagination Hook
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/usage-guide.mdx
This section compares manual pagination state management with the `usePagination` hook. The hook simplifies pagination logic by providing a structured `state` object with properties like `page`, `pageSize`, and `total`, and `actions` for operations such as `next`, `prev`, and `go`.
```tsx
// Not recommended
const [total, setTotal] = useState(100)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(10)
const pageCount = Math.ceil(total / pageSize)
const handlePageChange = (page) => {
console.log(page, pageSize, pageCount, total)
}
useUpdateEffect(() => {
handlePageChange(page)
}, [page])
```
```tsx
// Recommended
const [state, actions] = usePagination({
total: 100,
pageSize: 10,
onPageChange: (state) => {
console.log(state.page, state.pageSize, state.pageCount, state.total)
}
})
// `state` includes various pagination states
const { page, pageSize, pageCount, total, isFirstPage, isLastPage } = state
// `actions` can perform various pagination operations
actions.next() // Go to next page
actions.prev() // Go to previous page
actions.go(3) // Jump to page 3
actions.setPageSize(20) // Set number of items per page to 20
```
--------------------------------
### Usage Example for useSafeState Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-safe-state/index.mdx
Demonstrates how to use `useSafeState` with an initial object state and the `deep` comparison option enabled. It illustrates that setting a new value triggers a re-render, while setting an identical value (when `deep` is true) does not, thus optimizing performance.
```tsx
const [info, setInfo] = useSafeState({ name: 'Bob' }, { deep: true })
setInfo({ name: 'Amy' }) // Setting a new value will trigger a re-render
setInfo({ name: 'Amy' }) // Setting the "same" value again will not trigger a re-render when the deep option is enabled
```
--------------------------------
### Execute Side Effects Once on Mount and Unmount with useEffectOnce
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/usage-guide.mdx
`useEffectOnce` combines the functionalities of `useMount` and `useUnmount`, ensuring that an operation runs only once when the component mounts and its cleanup runs once when it unmounts. It simplifies scenarios requiring a single, complete side effect lifecycle.
```tsx
// Not recommended
useEffect(() => {
doSomething()
return () => clearSomething()
}, [])
```
```tsx
// Recommended
useEffectOnce(() => {
doSomething()
return () => clearSomething()
})
```
--------------------------------
### Using usePagingList for Paginated Data Fetching
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-paging-list/index.zh-cn.mdx
This example illustrates the core usage of `usePagingList`, demonstrating how to provide a `fetcher` function to retrieve paginated data and set the total count. It also shows how to configure integrated `useQuery`, `useForm`, and `usePagination` options, and specify fields that trigger immediate queries upon change.
```tsx
const {
form, pagination, selection,
list, refresh, loading
} = usePagingList(options)
// 传入一个接受 page, pageSize 分页参数的函数,它需要返回一个数据列表
// 在这个函数里面使用 setTotal 来设置数据总数,以便分页器能够正确显示总数
const { form, pagination, selection, list, refresh, loading } = usePagingList(
{
fetcher: async (payload) => {
const { page, pageSize, form, setTotal } = payload
const { list, total } = await fetchPaginationList({ page, pageSize })
setTotal(total)
return list
},
// 传入 useQuery 的配置项,如 refreshInterval 进行定时刷新
query: { refreshInterval: 3_000 },
// 传入 useForm 的配置项,如 initialValues 进行表单初始化
form: { initialValues: { name: '', select: '' } },
// 传入 usePagination 的配置项,如设置默认页码和每页显示数量
pagination: { page: 1, pageSize: 10 },
// 声明立即查询的表单字段,当表单字段变化时,会自动触发查询
immediateQueryKeys: ['select'],
},
)
```
--------------------------------
### Copy Text to Clipboard with useClipboard Hook
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/usage-guide.mdx
This snippet illustrates two methods for copying text to the clipboard. It contrasts the manual DOM manipulation or reliance on external libraries with the simplified approach offered by the `useClipboard` hook, which provides a robust and browser-compatible solution for clipboard operations.
```tsx
// Not recommended
const copyToClipboard = () => {
const input = document.createElement('input')
document.body.appendChild(input)
input.value = 'Hello, React'
input.select()
document.execCommand('copy')
document.body.removeChild(input)
}
// Not recommended, introduces additional dependencies leading to fragmented experience
import copy from 'copy-to-clipboard'
import CopyToClipboard from 'react-copy-to-clipboard'
```
```tsx
// Recommended
const clipboard = useClipboard()
clipboard.copy('Hello, React')
```
--------------------------------
### React useVirtualList Hook Usage Example
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-virtual-list/index.zh-cn.mdx
Demonstrates how to integrate and use the `useVirtualList` hook in a React component. It shows how to define container and wrapper refs, set a fixed item height, and render the virtualized list items using the returned `list` array.
```tsx
const containerRef = useRef(null)
const wrapperRef = useRef(null)
const [list, actions] = useVirtualList(largeList, {
// 或者直接使用 `querySelector` 的字符串: `#scroll-container`
containerTarget: containerRef,
// 或者直接使用 `querySelector` 的字符串: `#scroll-wrapper`
wrapperTarget: wrapperRef,
// 确保每个项目的高度为 48(包括 margin、padding 等),或者一个返回每个项目高度的函数
itemHeight: 48,
})
// actions.scrollTo(1000)
// actions.scrollToStart()
// actions.scrollToEnd()
// 使用 `list[0].data` 和 `list[0].index` 来渲染项目
return (
{list.map((item) => (
{item.data}
))}
)
```
--------------------------------
### useToggle Hook API Call Examples
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-toggle/index.mdx
Illustrates the two primary ways to call the `useToggle` hook: with a boolean initial state for `true`/`false` toggling, or with an array of two values for custom state management.
```tsx
const [bool, actions] = useToggle(bool)
const [value, actions] = useToggle([one, theOther])
```
--------------------------------
### Enable Caching and SWR Strategy in useQuery
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.mdx
This example illustrates how to enable caching functionality for the `useQuery` hook using `cacheKey` and `cacheExpirationTime`. It explains the SWR (Stale-While-Revalidate) strategy, where cached data is returned immediately while a background request updates the cache for freshness.
```TypeScript
const { loading, data, error } = useQuery(fetchData, {
cacheKey: 'cacheKey', // Cache key, can be a string or a function returning a string
cacheExpirationTime: 5 * 60 * 1000, // Maximum cache time, default 5 minutes, set `false` to disable
})
```
--------------------------------
### Optimize React Component Initialization with useCreation
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/usage-guide.mdx
`useCreation` is designed for one-time initialization of complex objects or lengthy operations, ensuring performance optimization and result stability across renders. It's a recommended alternative to `useMemo` for such scenarios, ensuring the result remains stable across different rendering cycles.
```tsx
// Not recommended
const heavyResult = useMemo(() => doHeavyWorkToInit(), [])
const dynamicResult = useMemo(() => doHeavyWorkToCreate(), [dependency])
```
```tsx
// Recommended
const heavyResult = useCreation(() => doHeavyWorkToInit())
const dynamicResult = useCreation(() => doHeavyWorkToCreate(), [dependency])
```
--------------------------------
### Customizing Visibility and Online Status for useQuery in Non-Web Environments
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.mdx
Provides an example for integrating `useQuery` in non-Web environments like React Native or Ink by allowing manual specification of `isVisible` and `isOnline` functions. It also demonstrates how to register custom focus and reconnect event handlers.
```ts
import { createReactNativeReFocusRegister } from '@shined/react-use'
import { AppState } from 'react-native'
const { loading, data, error } = useQuery(fetchData, {
isVisible: () => true, // Custom visibility determination function
isOnline: () => true, // Custom online status determination function
registerReConnect: createReactNativeReFocusRegister(AppState), // Built-in React Native network reconnection registration function
registerReFocus: (callback) => {}, // Custom focus event registration function
})
```
--------------------------------
### Manage Component Mount Side Effects with useMount Hook
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/usage-guide.mdx
This section demonstrates how to perform operations when a React component mounts. It contrasts the less semantic `useEffect` with an empty dependency array, which can have readability and maintenance issues, with the recommended `useMount` hook, which supports both synchronous and asynchronous functions.
```tsx
// Not recommended
useEffect(() => {
doSomething()
}, [])
```
```tsx
// Not recommended
useEffect(() => {
async function asyncWrapper() {
const result = await doSomethingAsync()
console.log(result)
}
asyncWrapper()
}, [])
```
```tsx
// Recommended
useMount(doSomething)
// Recommended
useMount(async () => {
const result = await doSomethingAsync()
console.log(result)
})
```
--------------------------------
### Define UseQueryCacheLike Interface for Custom Cache Providers
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.mdx
This API documentation defines the `UseQueryCacheLike` interface, which specifies the contract for custom cache providers used with the `useQuery` hook. It outlines the required `get`, `set`, `delete`, and `keys` methods, enabling integration with external storage solutions like `Map` or `localStorage`.
```APIDOC
export interface UseQueryCacheLike {
get(key: string): Data | undefined
set(key: string, value: Data): void
delete(key: string): void
keys(): IterableIterator
}
```
--------------------------------
### API: CreateSingleLoadingReturns Interface
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/create-single-loading/index.mdx
Defines the comprehensive set of functionalities returned by `createSingleLoading`. This includes React Hooks like `useAsyncFn` for binding async functions with loading states and `useLoading` for accessing the global loading state, as well as instance methods `set`, `get`, and `bind` for direct state manipulation and function binding.
```APIDOC
export interface CreateSingleLoadingReturns {
/**
* A Hook in React to use bound async function with loading state
*
* @param {AnyFunc} asyncFn - `AnyFunc`, the async function to bind, see {@link AnyFunc}
* @returns {UseAsyncFnExtendReturns} see {@link UseAsyncFnExtendReturns}
*/
useAsyncFn: (asyncFn: T) => UseAsyncFnExtendReturns
/**
* A Hook in React to use loading state
*
* @returns {boolean} `boolean`, the loading state
*/
useLoading(): boolean
/**
* Set the loading state via store via instance
*
* @param {boolean} value - `boolean`, the value to set
* @returns {void} `void`
*/
set: (value: boolean) => void
/**
* Get the loading state via store via instance
*
* @returns {boolean} `boolean`, the loading state
*/
get(): boolean
/**
* Bind the loading state to the async function via instance
*
* @param {AnyFunc} asyncFn - `AnyFunc`, the async function to bind, see {@link AnyFunc}
* @returns {AnyFunc} `AnyFunc`, same as `asyncFn` param, see {@link AnyFunc}
*/
bind: (asyncFn: T) => T
}
```
--------------------------------
### useWebObserver API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-web-observer/index.zh-cn.mdx
Detailed API documentation for the `useWebObserver` React hook, including interfaces for options and return values, and overloaded function signatures for different observer types.
```APIDOC
export interface UseWebObserverOptions {
/**
* Starts observing immediately after this function is called.
*
* @defaultValue true
*/
immediate?: boolean
}
export interface UseWebObserverReturns extends Pausable {
/**
* Ref to store the observer instance.
*/
observerRef: React.MutableRefObject
/**
* Checks if the current environment supports the observer.
*/
isSupported: boolean
}
export type WebObserverType =
| 'IntersectionObserver'
| 'MutationObserver'
| 'ResizeObserver'
| 'PerformanceObserver'
| 'ReportingObserver'
export function useWebObserver(
observer: 'IntersectionObserver',
target: Arrayable,
callback: IntersectionObserverCallback,
options?: UseWebObserverOptions,
initOptions?: IntersectionObserverInit,
observerOptions?: undefined,
): UseWebObserverReturns
export function useWebObserver(
observer: 'MutationObserver',
target: Arrayable,
callback: MutationCallback,
options?: UseWebObserverOptions,
initOptions?: undefined,
observerOptions?: MutationObserverInit,
): UseWebObserverReturns
export function useWebObserver(
observer: 'ResizeObserver',
target: Arrayable,
callback: ResizeObserverCallback,
options?: UseWebObserverOptions,
initOptions?: undefined,
observerOptions?: ResizeObserverOptions,
): UseWebObserverReturns
export function useWebObserver(
observer: 'PerformanceObserver',
target: undefined,
callback: PerformanceObserverCallback,
options?: UseWebObserverOptions,
initOptions?: undefined,
observerOptions?: PerformanceObserverInit,
): UseWebObserverReturns
export function useWebObserver(
observer: 'ReportingObserver',
target: undefined,
callback: ReportingObserverCallback,
options?: UseWebObserverOptions,
initOptions?: ReportingObserverOptions,
observerOptions?: undefined,
): UseWebObserverReturns
```
--------------------------------
### Illustrating Unnecessary Re-renders with useQuery
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/features/dependencies-collection.md
This example demonstrates a common scenario where `useQuery` returns multiple states (`data`, `loading`, `error`), but the user only consumes `run` and `loading`. Without dependency collection, any change to `data`, `error`, or `loading` triggers a re-render, even if the unused states change, leading to performance overhead.
```tsx
// Users actually only need the run operation and this one state of loading; they're not really concerned about error or data
const { run, loading } = useQuery(requestSomething, options)
// User executes the run operation
run()
// When `data`, `error`, or `loading` changes, an internal `setState` operation is triggered causing the component to re-render
```
--------------------------------
### Optimize React State Re-renders with useSafeState deep option
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/usage-guide.mdx
This example illustrates how `useSafeState` with the `deep: true` option can prevent unnecessary component re-renders when the state object's reference changes but its deep value remains the same. This optimization is particularly useful for complex or frequently updated state objects.
```tsx
const [state, setState] = useState({ count: 0 })
setState({ count: 0 }) // Triggers re-render
setState({ count: 0 }) // Triggers re-render
setState({ count: 0 }) // Triggers re-render
// Replace with
const [state, setState] = useSafeState({ count: 0 }, { deep: true })
setState({ count: 0 }) // Does not trigger re-render
setState({ count: 0 }) // Does not trigger re-render
setState({ count: 0 }) // Does not trigger re-render
// deep is an optional feature. When the state is simple and controlled, and the state's address changes frequently but the actual value does not change, it will significantly reduce the number of renders.
```
--------------------------------
### Pseudocode for Initializing and Refreshing States
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.zh-cn.mdx
The `initializing` and `refreshing` states are derived from the `loading` and `data` states of the `useQuery` hook. This pseudocode illustrates their logical relationship.
```ts
const initializing = Boolean(!data && loading)
const refreshing = Boolean(data && loading)
```
--------------------------------
### API: UseUserIdleOptions Interface Definition
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-user-idle/index.mdx
Defines the `UseUserIdleOptions` interface, which specifies the configurable parameters for the `useUserIdle` hook. These options include `events` to monitor user activity, `watchVisibility` for document focus, `initialState` for the hook's starting idle status, and `immediate` for controlling the initial reset behavior.
```APIDOC
export interface UseUserIdleOptions {
/**
* Event names that listen to for detected user activity
*
* @defaultValue ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel']
*/
events?: WindowEventName[]
/**
* Listen for document visibility change
*
* @defaultValue true
*/
watchVisibility?: boolean
/**
* Initial state of the ref idle
*
* @defaultValue false
*/
initialState?: boolean
/**
* Reset the idle state immediately
*
* @defaultValue true
*/
immediate?: boolean
}
```
--------------------------------
### useWebSocket Hook API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-web-socket/index.mdx
Provides the API signature for the `useWebSocket` hook, detailing its two primary usage patterns: initializing with a URL and options, or initializing with options and opening the connection later. It also describes the `WsUrl` parameter.
```APIDOC
useWebSocket(wsUrl: string, options?: object)
useWebSocket(options?: object)
.open(wsUrl: string)
WsUrl Connection String:
A WebSocket URL string.
```
--------------------------------
### Valid ElementTarget Examples with useTargetElement
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/features/element-target.md
Provides various valid examples of inputs for the `useTargetElement` Hook, showcasing how to pass React Refs, CSS selector strings, and getter functions (for SSR compatibility) to target different elements. It also notes examples that are not recommended due to potential SSR issues.
```tsx
const ref = useRef(null) //
const targetRef = useTargetElement(ref)
const targetRef = useTargetElement('#my-div')
const targetRef = useTargetElement('#my-div .container')
const targetRef = useTargetElement(() => window)
const targetRef = useTargetElement(() => document.getElementById('my-div'))
// Not recommended, may cause SSR issues
const targetRef = useTargetElement(window)
// Not recommended, may cause SSR issues
const targetRef = useTargetElement(document.getElementById('my-div'))
```
--------------------------------
### Basic useQuery Usage
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.zh-cn.mdx
When the component mounts, data fetching is automatically triggered (the `immediate` option defaults to `true`), returning data, loading status, and error information. This functionality is supported by `useAsyncFn`.
```tsx
// 这里的 `fetchData` 被叫做 `Fetcher`,是一个请求库无关、返回任意 Promise 的异步函数
// Fetcher 函数可以通过 fetch、axios、graphql 等方式进行自定义实现
const { loading, data, error } = useQuery(fetchData)
// 加载中、错误 UI 处理
if (loading) return
if (error) return
// 渲染数据
return
{data}
```
--------------------------------
### Valid ElementTarget Examples for useTargetElement Hook
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/zh-cn/docs/features/element-target.md
This snippet provides various valid examples of `ElementTarget` inputs for the `useTargetElement` hook. It showcases how to pass React Refs, CSS selector strings, and getter functions (which are useful for SSR). It also highlights examples that are not recommended due to potential SSR issues when directly passing global objects or DOM elements.
```tsx
const ref = useRef(null) //
const targetRef = useTargetElement(ref)
const targetRef = useTargetElement('#my-div')
const targetRef = useTargetElement('#my-div .container')
const targetRef = useTargetElement(() => window)
const targetRef = useTargetElement(() => document.getElementById('my-div'))
// 不推荐,会引起 SSR 问题
const targetRef = useTargetElement(window)
// 不推荐,会引起 SSR 问题
const targetRef = useTargetElement(document.getElementById('my-div'))
```
--------------------------------
### useWindowSize Hook API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-window-size/index.mdx
Detailed API documentation for the `useWindowSize` React Hook, outlining the configurable options and the structure of the returned object. It includes definitions for input parameters and the output interface.
```APIDOC
### Options
export interface UseWindowSizeOptions {
/**
* The initial width of the window.
*
* @defaultValue Number.POSITIVE_INFINITY
*/
initialWidth?: number
/**
* The initial height of the window.
*
* @defaultValue Number.POSITIVE_INFINITY
*/
initialHeight?: number
/**
* Whether to listen to orientation changes.
*
* @defaultValue true
*/
listenOrientation?: boolean
/**
* Whether to include the scrollbar width.
*
* @defaultValue true
*/
includeScrollbar?: boolean
}
### Returns
export interface WindowSize {
width: number
height: number
}
export interface UseWindowSizeReturns extends Size {
/**
* Update the window size.
*/
update(): void
}
```
--------------------------------
### Example: Filtering Async Operations with useVersionedAction
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-versioned-action/index.zh-cn.mdx
This example illustrates how to use `useVersionedAction` to prevent 'stale' operations from causing UI issues. When `doSomething()` is called repeatedly, `incVersion()` generates a new version, and `runVersionedAction()` ensures that `setResult` is only called for the latest version of the asynchronous `fetchSomething()` operation.
```tsx
const [incVersion, runVersionedAction] = useVersionedAction()
const doSomething = async () => {
// Increment the version number using incVersion()
const version = incVersion()
// Asynchronous operation, e.g., fetching data
const result = await fetchSomething()
// Ensure only the latest operation is executed using runVersionedAction()
runVersionedAction(version, async () => {
setResult(result)
})
}
```
--------------------------------
### Example Usage of usePausable Hook in React Component
Source: https://github.com/sheinsight/react-use/blob/main/docs/docs/en/docs/features/pausable.md
Provides a complete React component example demonstrating how to integrate and use the `usePausable` hook. It shows how to obtain the `isActive`, `pause`, and `resume` functions from the hook's return and bind them to UI elements like buttons for interactive control.
```tsx
import { usePausable } from '@shined/react-use'
function App() {
// pausable can be obtained from the return of some hooks
// const { isActive, pause, resume, ...others } = useMouse()
const { isActive, pause, resume } = usePausable(false)
function check() {
if (isActive()) {
// Do something
}
}
return (
)
}
```
--------------------------------
### useWebObserver Hook API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-web-observer/index.mdx
Comprehensive API documentation for the `useWebObserver` React Hook, including its options, return values, and various function overloads for different Web Observer types.
```APIDOC
export interface UseWebObserverOptions {
/**
* Start the observer immediate after calling this function
*
* @defaultValue true
*/
immediate?: boolean
}
export interface UseWebObserverReturns extends Pausable {
/**
* ref that holds the observer instance
*/
observerRef: React.MutableRefObject
/**
* Check if the observer is supported in the current environment
*/
isSupported: boolean
}
export type WebObserverType =
| 'IntersectionObserver'
| 'MutationObserver'
| 'ResizeObserver'
| 'PerformanceObserver'
| 'ReportingObserver'
export function useWebObserver(
observer: 'IntersectionObserver',
target: Arrayable,
callback: IntersectionObserverCallback,
options?: UseWebObserverOptions,
initOptions?: IntersectionObserverInit,
observerOptions?: undefined,
): UseWebObserverReturns
export function useWebObserver(
observer: 'MutationObserver',
target: Arrayable,
callback: MutationCallback,
options?: UseWebObserverOptions,
initOptions?: undefined,
observerOptions?: MutationObserverInit,
): UseWebObserverReturns
export function useWebObserver(
observer: 'ResizeObserver',
target: Arrayable,
callback: ResizeObserverCallback,
options?: UseWebObserverOptions,
initOptions?: undefined,
observerOptions?: ResizeObserverOptions,
): UseWebObserverReturns
export function useWebObserver(
observer: 'PerformanceObserver',
target: undefined,
callback: PerformanceObserverCallback,
options?: UseWebObserverOptions,
initOptions?: undefined,
observerOptions?: PerformanceObserverInit,
): UseWebObserverReturns
export function useWebObserver(
observer: 'ReportingObserver',
target: undefined,
callback: ReportingObserverCallback,
options?: UseWebObserverOptions,
initOptions?: ReportingObserverOptions,
observerOptions?: undefined,
): UseWebObserverReturns
```
--------------------------------
### useGetterRef Hook API Overview
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-getter-ref/index.mdx
Provides a structured overview of the `useGetterRef` React Hook's API, detailing its parameters and the components of its return value.
```APIDOC
useGetterRef(initialValue)
Parameters:
initialValue: Initial value of the ref.
Returns:
Type: UseGetterRefReturns
Description: A tuple containing:
- ref: React.MutableRefObject - A mutable ref object that can be used to store a value.
- getter: () => T - A getter function that returns the current value of the ref.
```
--------------------------------
### useStateHistory Hook Usage Example
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-state-history/index.mdx
Demonstrates how to destructure the return value of the useStateHistory hook, which includes history manipulation utilities and a Pausable instance.
```tsx
const { ...history, ...pausable } = useStateHistory(state, options)
```
--------------------------------
### useVirtualList Hook API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-virtual-list/index.mdx
Detailed API documentation for the `useVirtualList` React hook, including its signature, input options, and return values.
```APIDOC
const [list, actions] = useVirtualList(largeList, options)
```
```APIDOC
LargeList:
An arbitrary valid array containing a large amount of data.
```
```APIDOC
Options:
interface UseVirtualListBaseOptions {
/**
* The container element, of type ElementTarget, typically the scrollable element.
*/
containerTarget: NonNullable>
/**
* The wrapper element, of type ElementTarget, typically the element containing all items.
*
* MarginTop and height (marginLeft and width for horizontal scrolling) will be set to the total height (width) of all items.
*/
wrapperTarget: NonNullable>
/**
* The number of items to additionally render outside the viewport (above and below for vertical scrolling, left and right for horizontal).
*
* @defaultValue 5
*/
overscan?: number
}
interface UseVerticalVirtualListOptions extends UseVirtualListBaseOptions {
/**
* The height of each item, or a function returning the height of each item, accepting parameters index and item.
*
* When `itemHeight` is set, the list is in vertical rendering mode, with higher priority than `itemWidth`.
*/
itemHeight: number | ((index: number, item: D) => number)
}
interface UseHorizontalVirtualListOptions extends UseVirtualListBaseOptions {
/**
* The width of each item, or a function returning the width of each item, accepting parameters index and item.
*
* When `itemWidth` is set and `itemHeight` is not, the list is in horizontal rendering mode.
*/
itemWidth: number | ((index: number, item: D) => number)
}
export type UseVirtualListOptions = UseVerticalVirtualListOptions | UseHorizontalVirtualListOptions
```
```APIDOC
Returns:
export interface UseVirtualListReturnsActions {
/**
* Scrolls to the item at the specified index.
*
* @param {Number} index The index of the item to scroll to.
*/
scrollTo: (index: number) => void
/**
* Scrolls to the start of the list, automatically using vertical or horizontal scrolling based on the options.
*/
scrollToStart: () => void
/**
* Scrolls to the end of the list, automatically using vertical or horizontal scrolling based on the options.
*/
scrollToEnd: () => void
}
export interface UseVirtualListReturnsListItem {
/**
* The original data item of the project.
*/
data: D
/**
* The original array index of the project.
*/
index: number
}
export type UseVirtualListReturns = readonly [
/**
* The array of items of the virtual list, i.e., the actual items that are being rendered, including the visible area and the additional rendering area.
*/
list: UseVirtualListReturnsListItem[],
/**
* A collection of methods for operating the virtual list.
*/
UseVirtualListReturnsActions,
]
```
--------------------------------
### useMediaQuery API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-media-query/index.mdx
Detailed API documentation for the `useMediaQuery` React Hook, including parameter descriptions and return types.
```APIDOC
useMediaQuery Hook:
Parameters:
queryString:
Type: string | string[]
Description: A media query string, or an array of media query strings.
options:
Type: UseMediaQueryOptions (extends AddEventListenerOptions)
Description: Options of useEventListener. See useEventListener#options for more details.
Returns:
Type: boolean | boolean[]
Description:
If queryString is a string, returns a boolean value that indicates whether the media query matches.
If queryString is an array, returns an array of boolean values that indicate whether the media queries match.
```
--------------------------------
### UseWebObserverOptions Interface
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-intersection-observer/index.zh-cn.mdx
Defines the `UseWebObserverOptions` interface, which includes common options for web observer hooks, such as `immediate` to control when observation starts after the function call.
```TypeScript
export interface UseWebObserverOptions {
/**
* 调用此函数后立即开始观察
*
* @defaultValue true
*/
immediate?: boolean
}
```
--------------------------------
### Basic Usage of useNow Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-now/index.mdx
Demonstrates how to use the `useNow` hook to get the current date, and how to destructure it to access `now` and control functions when the `controls` option is enabled.
```tsx
const now = useNow(options)
const { now, ...controls } = useNow({ controls: true, ...otherOptions })
```
--------------------------------
### useMediaQuery API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-media-query/index.zh-cn.mdx
Detailed API documentation for the `useMediaQuery` React Hook, outlining its parameters, options, and return values.
```APIDOC
useMediaQuery Hook:
Parameters:
queryString:
Type: string | string[]
Description: A CSS media query string, or an array of media query strings.
options:
Type: UseMediaQueryOptions
Description: AddEventListenerOptions for useEventListener. See useEventListener#options for details.
Returns:
Type: boolean | boolean[]
Description: If queryString is a string, returns a boolean indicating if the media query matches. If queryString is an array, returns an array of booleans.
Type Definition: export type UseMediaQueryReturns = R extends T[] ? boolean[] : boolean
```
--------------------------------
### useRafLoop Options API Definition
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-raf-loop/index.mdx
Describes the `UseRafLoopOptions` interface, which allows configuration of the animation loop with properties like `fpsLimit`, `immediate` start, and `immediateCallback` execution.
```APIDOC
UseRafLoopOptions:
fpsLimit?: number - The maximum fps limit (defaultValue: undefined)
immediate?: boolean - Whether to start the interval immediately on mounted (defaultValue: true)
immediateCallback?: boolean - Whether to execute the callback immediately before the interval starts (defaultValue: false)
```
--------------------------------
### Basic Usage of useReactive Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-reactive/index.mdx
Demonstrates how to import and use the `useReactive` hook with an initial state and a `create` function from `@shined/reactive`.
```tsx
import { create } from '@shined/reactive';
const [state, mutate] = useReactive(initialState, { create })
```
--------------------------------
### useCreation Hook Parameter Details
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-creation/index.mdx
Provides detailed descriptions for the `factoryFn` and `deps` parameters used by the `useCreation` React Hook, explaining their roles in memoization.
```APIDOC
FactoryFn:
A function that returns the value to memoize.
Deps:
An array of dependencies that trigger the re-creation of the memoized value.
```
--------------------------------
### React Hook: Get Document Visibility State
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-document-visibility/index.mdx
Demonstrates the basic usage of the `useDocumentVisibility` hook, which returns the current visibility state of the document. It can optionally take a callback function.
```tsx
const visibility = useDocumentVisibility(callback)
```
--------------------------------
### useLayoutMount Hook API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-layout-mount/index.mdx
Detailed API documentation for the `useLayoutMount` React Hook, including its parameters and their behavior.
```APIDOC
useLayoutMount(callback, strictOnce)
callback: function - A function that will be called when the component mounts (useLayoutEffect), can be async.
strictOnce: boolean - Indicates whether the handler should be called only once in Strict Mode of React 18. Default is false.
Warning: This option is NOT recommended as it damages the original intention of the Strict Mode of React 18.
```
--------------------------------
### Using useRafState for Performance Optimization
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-raf-state/index.mdx
Demonstrates how to use `useRafState` to update state in the next animation frame, improving performance. Includes an example with the `deep` option for further optimization, inherited from `useSafeState`.
```tsx
// Use in scenarios where performance optimization is needed
const [state, setState] = useRafState({ isScrolling: false })
// You can use the `deep` option inherited from `useSafeState` to further reduce rendering and thus optimize performance
const [{ x, y }, setPosition] = useRafState({ x: 0, y: 0 }, { deep: true })
```
--------------------------------
### Basic Usage of useBreakpoints Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-breakpoints/index.mdx
Illustrates the typical invocation of the `useBreakpoints` hook, showing how it's used with a `breakpoints` object and an optional `options` configuration to get breakpoint states.
```tsx
const bps = useBreakpoints(breakpoints, options)
```
--------------------------------
### useKeyStatus API Parameters and Returns Documentation
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-key-status/index.mdx
Detailed documentation for the `useKeyStatus` React Hook's parameters and return value, referencing related types and documentation from `useKeyStroke`.
```APIDOC
useKeyStatus Parameters:
keyFilter:
Description: See KeyFilter of `useKeyStroke` for more details.
handler:
Type: UseKeyStatusHandler
Description: See Handler of `useKeyStroke` for more details.
options:
Type: UseKeyStatusOptions
Description: See Options of `useKeyStroke` for more details.
useKeyStatus Returns:
Type: boolean
Description: A boolean value that indicates the press status of the key.
```
--------------------------------
### Basic Usage of useQuery
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.mdx
When the component is mounted, it automatically triggers data fetching and returns data, loading status, and error information, supported by [useAsyncFn](/reference/use-async-fn).
```tsx
// fetchData is independent of the request library, it can be any async function that returns a Promise, which can be implemented by fetch, axios, graphql, etc.
const { loading, data, error } = useQuery(fetchData)
// Loading and error UI handling
if (loading) return
if (error) return
// Rendering data
return
{data}
```
--------------------------------
### useParentElement Hook Usage Example
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-parent-element/index.mdx
Illustrates the basic usage of the `useParentElement` React Hook to retrieve the parent `HTMLElement` of a target element. The hook returns `null` if the target element does not have a parent or is not valid.
```tsx
const parentElement = useParentElement(elementTarget)
```
--------------------------------
### Get Text Selection State with useTextSelection Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-text-selection/index.mdx
Demonstrates how to destructure the return values from the `useTextSelection` React Hook to access selected text, bounding rectangles, ranges, and a reference to the selection object.
```tsx
const { text, rects, ranges, selectionRef } = useTextSelection()
```
--------------------------------
### useFullscreen Hook Basic Usage
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-fullscreen/index.mdx
Illustrates the basic syntax for integrating the `useFullscreen` React Hook into a component, showing how to initialize it with a target element and options.
```TypeScript
const fs = useFullscreen(elementTarget, options)
```
--------------------------------
### useSpringValue Hook Signature
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-spring-value/index.mdx
Illustrates the basic signature for the `useSpringValue` React Hook. It accepts a `start` value (number) and an `end` value (number) for the spring animation, along with an `options` object for configuration.
```tsx
const spring = useSpringValue(start, end, options)
```
--------------------------------
### UseCountdownOptions Type Definition
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-countdown/index.mdx
Defines the UseCountdownOptions type, detailing the configurable parameters for the useCountdown hook, including immediate start, control exposure, update interval, and callback functions for updates and stops.
```tsx
export type UseCountdownOptions = {
/**
* whether to start the countdown immediately
*
* @defaultValue true
*/
immediate?: boolean
/**
* whether to expose the controls
*
* @defaultValue false
*/
controls?: Controls
/**
* the interval to update the countdown
*
* @defaultValue 'requestAnimationFrame'
*/
interval?: 'requestAnimationFrame' | number
/**
* a callback function to be called when the countdown is updated
*/
onUpdate?: (ms: number, seconds: number) => void
/**
* a callback function to be called when the countdown is stopped
*/
onStop?(): void
}
```
--------------------------------
### useQuery Lifecycle Callbacks
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-query/index.mdx
`useQuery` provides rich lifecycle support, supported by [useAsyncFn](/reference/use-async-fn), including:
```ts
const { loading, data, error } = useQuery(fetchData, {
// Before the operation
onBefore: (data, params) => console.log('before', data, params),
// After the operation
onSuccess: (data, params) => console.log('success', data, params),
// In case of failure
onError: (error, params) => console.log('error', error, params),
// Upon completion
onFinally: (data, params) => console.log('finally', data, error, params),
// When cancelling
onCancel: (data, params) => console.log('cancel', data, error, params),
// Manual data or parameter modification
onMutate: (data, params) => console.log('mutate', data, params),
// Refreshing
onRefresh: (data, params) => console.log('refresh', data, params),
})
```
--------------------------------
### useLoremIpsum Hook API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-lorem-ipsum/index.mdx
Detailed API documentation for the `useLoremIpsum` React Hook, including its parameters and return value.
```APIDOC
useLoremIpsum(length: number): string
length: number - The number of sentences to generate. (Default: 1)
useLoremIpsum(options: UseLoremIpsumOptions): string
options: UseLoremIpsumOptions - An object to configure text generation.
Returns: string - The generated Lorem Ipsum text.
```
--------------------------------
### Basic Usage of useWindowSize Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-window-size/index.mdx
Demonstrates how to call the `useWindowSize` hook to get the current window dimensions. This hook returns an object containing the window's width and height, and a method to manually update the size.
```TypeScript
const size = useWindowSize(options)
```
--------------------------------
### Basic Usage of useMemoize Hook
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-memoize/index.mdx
Illustrates the fundamental way to use the `useMemoize` React Hook, showing its return value and parameters.
```tsx
const cachedFn = useMemoize(fnToBeCached, options)
```
--------------------------------
### Basic and Controlled useInterval Hook Usage
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-interval/index.mdx
Demonstrates how to use the `useInterval` hook in its basic form to get a simple count, and with the `controls` option to access additional actions like `reset` and Pausable controls.
```tsx
const count = useInterval(interval)
const { count, reset, ...controls } = useInterval(interval, { controls: true })
```
--------------------------------
### useKeyStroke Hook API Reference
Source: https://github.com/sheinsight/react-use/blob/main/packages/react-use/src/use-key-stroke/index.mdx
Detailed API documentation for the `useKeyStroke` React Hook, including its signatures, parameters, and return value.
```APIDOC
useKeyStroke(handler: UseKeyStrokeHandler, options?: UseKeyStrokeOptions): Function
useKeyStroke(keyFilter: KeyFilter, handler: UseKeyStrokeHandler, options?: UseKeyStrokeOptions): Function
Parameters:
handler: UseKeyStrokeHandler
Description: The function to be called when a key stroke is detected.
keyFilter: KeyFilter (optional)
Description: Specifies which keys to listen for. Can be true (all keys), a string (single key), an array of strings (multiple keys), or a KeyPredicate function.
options: UseKeyStrokeOptions (optional)
Description: Configuration options for the event listener.
Returns:
Function: A function that, when called, stops listening for key strokes.
```