### Install usehooks-ts via npm Source: https://usehooks-ts.com/introduction/introduction This command installs the usehooks-ts library, a collection of React hooks, into your project using the npm package manager. It's the first step to integrate the library into your React application. ```Shell npm install usehooks-ts ``` -------------------------------- ### React useCountdown Hook Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-countdown This example demonstrates how to integrate and use the `useCountdown` hook within a React component. It shows how to initialize the countdown with a starting value and an adjustable interval, and provides buttons to start, stop, and reset the countdown, along with an input to change the interval dynamically. ```TypeScript import { useState } from 'react' import type { ChangeEvent } from 'react' import { useCountdown } from 'usehooks-ts' export default function Component() { const [intervalValue, setIntervalValue] = useState(1000) const [count, { startCountdown, stopCountdown, resetCountdown }] = useCountdown({ countStart: 60, intervalMs: intervalValue, }) const handleChangeIntervalValue = (event: ChangeEvent) => { setIntervalValue(Number(event.target.value)) } return (

Count: {count}

) } ``` -------------------------------- ### React Hook: useHover Basic Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-hover This example demonstrates how to import and use the `useHover` hook within a functional React component. It shows how to associate a `useRef` with a DOM element and dynamically display its hover state. ```TypeScript import { useRef } from 'react' import { useHover } from 'usehooks-ts' export default function Component() { const hoverRef = useRef(null) const isHover = useHover(hoverRef) return (
{`The current div is ${isHover ? `hovered` : `unhovered`}`}
) } ``` -------------------------------- ### React Component Example with useStep Hook Source: https://usehooks-ts.com/introduction/react-hook/use-step Illustrates how to integrate and utilize the `useStep` hook within a functional React component. It demonstrates initializing the hook with a maximum step, accessing the current step and helper functions, and implementing buttons to navigate through steps, reset, or set a specific step. ```TypeScript import { useStep } from 'usehooks-ts' export default function Component() { const [currentStep, helpers] = useStep(5) const { canGoToPrevStep, canGoToNextStep, goToNextStep, goToPrevStep, reset, setStep, } = helpers return ( <>

Current step is {currentStep}

Can go to previous step {canGoToPrevStep ? 'yes' : 'no'}

Can go to next step {canGoToNextStep ? 'yes' : 'no'}

) } ``` -------------------------------- ### React Component Example for useCopyToClipboard Source: https://usehooks-ts.com/introduction/react-hook/use-copy-to-clipboard Illustrates how to use the `useCopyToClipboard` hook within a React functional component. It demonstrates how to call the `copy` function with text and handle the returned Promise for success or error logging. ```TypeScript import { useCopyToClipboard } from 'usehooks-ts' export default function Component() { const [copiedText, copy] = useCopyToClipboard() const handleCopy = (text: string) => () => { copy(text) .then(() => { console.log('Copied!', { text }) }) .catch(error => { console.error('Failed to copy!', error) }) } return ( <>

Click to copy:

Copied value: {copiedText ?? 'Nothing is copied yet!'}

) } ``` -------------------------------- ### Example Usage of useMap Hook in React Source: https://usehooks-ts.com/introduction/react-hook/use-map Demonstrates how to initialize and interact with the `useMap` hook, including adding new entries, resetting the map, setting multiple entries at once, and removing specific entries from the map state within a React component. It showcases the basic API actions provided by the hook. ```TypeScript import { Fragment } from 'react' import { useMap } from 'usehooks-ts' export default function Component() { const [map, actions] = useMap([['key', '🆕']]) const set = () => { actions.set(String(Date.now()), '📦') } const setAll = () => { actions.setAll([ ['hello', '👋'], ['data', '📦'], ]) } const reset = () => { actions.reset() } const remove = () => { actions.remove('hello') } return (
        Map (
        {Array.from(map.entries()).map(([key, value]) => (
          {`\n  ${key}: ${value}`}
        ))}
        
)
) } ``` -------------------------------- ### React Component Example with useToggle Source: https://usehooks-ts.com/introduction/react-hook/use-toggle Illustrates how to integrate and interact with the `useToggle` hook within a React functional component. It shows how to get the current state, toggle it, and explicitly set it to true or false, including a custom toggle function. ```TypeScript import { useToggle } from 'usehooks-ts' export default function Component() { const [value, toggle, setValue] = useToggle() // Just an example to use "setValue" const customToggle = () => { setValue((x: boolean) => !x) } return ( <>

Value is {value.toString()}

) } ``` -------------------------------- ### React Hook: useScreen Basic Usage Source: https://usehooks-ts.com/introduction/react-hook/use-screen This example demonstrates how to import and integrate the `useScreen` custom hook into a React functional component. It shows how to retrieve and display the current screen dimensions and properties as a JSON string. ```TypeScript import { useScreen } from 'usehooks-ts' export default function Component() { const screen = useScreen() return (
The current window dimensions are:{' '} {JSON.stringify(screen, null, 2)}
) } ``` -------------------------------- ### React useCounter Hook Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-counter This snippet demonstrates how to integrate and use the `useCounter` hook within a React component. It shows how to destructure the `count`, `setCount`, `increment`, `decrement`, and `reset` functions, and how to bind them to UI elements for interactive counter management. It also includes an example of using `setCount` with a functional update. ```TypeScript import { useCounter } from 'usehooks-ts' export default function Component() { const { count, setCount, increment, decrement, reset } = useCounter(0) const multiplyBy2 = () => { setCount((x: number) => x * 2) } return ( <>

Count is {count}

) } ``` -------------------------------- ### React useEventListener Hook Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-event-listener This example demonstrates how to use the `useEventListener` hook in a React component to attach event listeners to different targets: the window for scroll events, the document for visibility changes, and a specific button element for click events. It showcases the flexibility of the hook in handling various event types and targets. ```TypeScript import { useRef } from 'react' import { useEventListener } from 'usehooks-ts' export default function Component() { // Define button ref const buttonRef = useRef(null) const documentRef = useRef(document) const onScroll = (event: Event) => { console.log('window scrolled!', event) } const onClick = (event: Event) => { console.log('button clicked!', event) } const onVisibilityChange = (event: Event) => { console.log('doc visibility changed!', { isVisible: !document.hidden, event, }) } // example with window based event useEventListener('scroll', onScroll) // example with document based event useEventListener('visibilitychange', onVisibilityChange, documentRef) // example with element based event useEventListener('click', onClick, buttonRef) return (
) } ``` -------------------------------- ### React useOnClickOutside Hook Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-on-click-outside Demonstrates how to integrate and use the `useOnClickOutside` hook in a React component. It sets up a ref for a button and defines two handlers: one for clicks inside the button and another for clicks outside, logging messages to the console for each. ```TypeScript import { useRef } from 'react' import { useOnClickOutside } from 'usehooks-ts' export default function Component() { const ref = useRef(null) const handleClickOutside = () => { // Your custom logic here console.log('clicked outside') } const handleClickInside = () => { // Your custom logic here console.log('clicked inside') } useOnClickOutside(ref, handleClickOutside) return ( ) } ``` -------------------------------- ### Example Usage of useLocalStorage Hook Source: https://usehooks-ts.com/introduction/react-hook/use-local-storage This snippet demonstrates how to use the `useLocalStorage` hook to manage a counter value that persists across page reloads. It shows how to initialize the state, update it, and remove it from local storage using the returned functions. ```TypeScript import { useLocalStorage } from 'usehooks-ts' export default function Component() { const [value, setValue, removeValue] = useLocalStorage('test-key', 0) return (

Count: {value}

) } ``` -------------------------------- ### Example Usage of useIntersectionObserver Hook in React Source: https://usehooks-ts.com/introduction/react-hook/use-intersection-observer This code snippet demonstrates how to integrate and use the `useIntersectionObserver` hook within a React component. It sets up multiple sections and logs whether each section is currently intersecting with the viewport, showcasing the hook's primary functionality for visibility detection. ```TypeScript import { useIntersectionObserver } from 'usehooks-ts' const Section = (props: { title: string }) => { const { isIntersecting, ref } = useIntersectionObserver({ threshold: 0.5, }) console.log(`Render Section ${props.title}`, { isIntersecting, }) return (
{props.title}
) } export default function Component() { return ( <> {Array.from({ length: 5 }).map((_, index) => (
))} ) } ``` -------------------------------- ### Example Usage of useScript Hook in React Source: https://usehooks-ts.com/introduction/react-hook/use-script This snippet demonstrates how to use the `useScript` hook to dynamically load an external JavaScript library (jQuery in this case). It shows how to track the script's loading status and execute code once the script is 'ready'. The `removeOnUnmount` option is set to `false` to keep the script in the DOM, and it includes a type declaration for jQuery. ```typescript import { useEffect } from 'react' import { useScript } from 'usehooks-ts' // it's an example, use your types instead declare const jQuery: any export default function Component() { // Load the script asynchronously const status = useScript(`https://code.jquery.com/jquery-3.5.1.min.js`, { removeOnUnmount: false, id: 'jquery', }) useEffect(() => { if (typeof jQuery !== 'undefined') { // jQuery is loaded => print the version // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access alert(jQuery.fn.jquery) } }, [status]) return (

{`Current status: ${status}`}

{status === 'ready' &&

You can use the script here.

}
) } ``` -------------------------------- ### React Hook: useHover API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-hover Formal API documentation for the `useHover` hook, detailing its signature, generic type parameters, input parameters (with their types and descriptions), and the return value. ```APIDOC useHover(elementRef: RefObject): boolean Description: Custom hook that tracks whether a DOM element is being hovered over. Type Parameters: T: extends HTMLElement = HTMLElement Description: The type of the DOM element. Defaults to `HTMLElement`. Parameters: elementRef: RefObject Description: The ref object for the DOM element to track. Returns: boolean Description: A boolean value indicating whether the element is being hovered over. ``` -------------------------------- ### React Component Example with useInterval Source: https://usehooks-ts.com/introduction/react-hook/use-interval This example demonstrates how to use the `useInterval` hook within a React functional component to create a counter that updates at a dynamic delay. It includes controls to play/pause the interval and adjust its speed. ```TypeScript import { useState } from 'react' import type { ChangeEvent } from 'react' import { useInterval } from 'usehooks-ts' export default function Component() { // The counter const [count, setCount] = useState(0) // Dynamic delay const [delay, setDelay] = useState(1000) // ON/OFF const [isPlaying, setPlaying] = useState(false) useInterval( () => { // Your custom logic here setCount(count + 1) }, // Delay in milliseconds or null to stop it isPlaying ? delay : null, ) const handleChange = (event: ChangeEvent) => { setDelay(Number(event.target.value)) } return ( <>

{count}

) } ``` -------------------------------- ### useStep Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-step Detailed API documentation for the `useStep` custom hook, outlining its parameters, return type, and the structure of the `UseStepActions` object, which provides methods for step navigation and control. ```APIDOC useStep(maxStep: number): [number, UseStepActions] Description: Custom hook that manages and navigates between steps in a multi-step process. Parameters: maxStep: number - The maximum step in the process. Returns: [number, UseStepActions] - An tuple containing the current step and helper functions for navigating steps. Type alias: UseStepActions: Object Description: Represents the second element of the output of the useStep hook. Properties: canGoToNextStep: boolean - Check if the next step is available. canGoToPrevStep: boolean - Check if the previous step is available. goToNextStep: () => void - Go to the next step in the process. goToPrevStep: () => void - Go to the previous step in the process. reset: () => void - Reset the step to the initial step. setStep: Dispatch> - Set the current step to a specific value. ``` -------------------------------- ### useIsClient Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-is-client Detailed API documentation for the `useIsClient` custom React hook, outlining its signature, return type, and a description of its functionality. This section clarifies what the hook provides and how to interpret its output. ```APIDOC useIsClient(): boolean Description: Custom hook that determines if the code is running on the client side (in the browser). Returns: boolean - A boolean value indicating whether the code is running on the client side. ``` -------------------------------- ### Example: Use useClickAnyWhere in a React Component Source: https://usehooks-ts.com/introduction/react-hook/use-click-any-where Demonstrates how to integrate the `useClickAnyWhere` hook into a React functional component to track click events anywhere on the document and update a state variable. This example shows a simple click counter. ```TypeScript import { useState } from 'react' import { useClickAnyWhere } from 'usehooks-ts' export default function Component() { const [count, setCount] = useState(0) useClickAnyWhere(() => { setCount(prev => prev + 1) }) return

Click count: {count}

} ``` -------------------------------- ### useReadLocalStorage Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-read-local-storage Detailed API documentation for the `useReadLocalStorage` hook, outlining its overloaded signatures, type parameters, input parameters with their types and descriptions, and the possible return values. It also includes the definition for the `Options` type alias used for configuring the hook's behavior. ```APIDOC ▸ useReadLocalStorage(key, options): T | null | undefined Custom hook that reads a value from localStorage, closely related to useLocalStorage(). Type parameters: T: The type of the stored value. Parameters: key: string - The key associated with the value in local storage. options: Options - Additional options for reading the value (optional). Returns: T | null | undefined - The stored value, or null if the key is not present or an error occurs. ▸ useReadLocalStorage(key, options?): T | null Custom hook that reads a value from localStorage, closely related to useLocalStorage(). Type parameters: T: The type of the stored value. Parameters: key: string - The key associated with the value in local storage. options?: Partial> - Additional options for reading the value (optional). Returns: T | null - The stored value, or null if the key is not present or an error occurs. Type aliases: Ƭ Options: Object Represents the type for the options available when reading from local storage. Type parameters: T: T - The type of the stored value. InitializeWithValue: extends boolean | undefined Type declaration: deserializer?: (value: string) => T - Custom deserializer function to convert the stored string value to the desired type (optional). initializeWithValue: InitializeWithValue - If true (default), the hook will initialize reading the local storage. In SSR, you should set it to false, returning undefined initially. ``` -------------------------------- ### useMediaQuery Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-media-query Detailed API documentation for the `useMediaQuery` hook, outlining its function signature, parameters, return type, and the structure of the `UseMediaQueryOptions` type alias with its properties and default values. ```APIDOC useMediaQuery: signature: (query: string, options?: UseMediaQueryOptions) => boolean description: Custom hook that tracks the state of a media query using the Match Media API. parameters: query: type: string description: The media query to track. options: type: UseMediaQueryOptions description: The options for customizing the behavior of the hook (optional). returns: type: boolean description: The current state of the media query (true if the query matches, false otherwise). UseMediaQueryOptions (Type alias): type: Object description: Hook options. properties: defaultValue: type: boolean description: The default value to return if the hook is being run on the server. Default: false initializeWithValue: type: boolean description: If true (default), the hook will initialize reading the media query. In SSR, you should set it to false, returning options.defaultValue or false initially. Default: true ``` -------------------------------- ### useDocumentTitle Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-document-title Detailed API documentation for the `useDocumentTitle` hook, including its parameters, their types, descriptions, and the return type. ```APIDOC ▸ useDocumentTitle(title, options?): void Custom hook that sets the document title. Parameters: | Name | Type | Description | | --- | --- | --- | | `title` | `string` | The title to set. | | `options?` | `UseDocumentTitleOptions` | The options. | Returns: `void` ``` -------------------------------- ### useMap Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-map Detailed API documentation for the `useMap` React hook, including its type parameters, function parameters, return types, and associated type aliases (`MapOrEntries`, `UseMapActions`) for comprehensive map state management. ```APIDOC useMap(initialState?): UseMapReturn Description: Custom hook that manages a key-value Map state with setter actions. Type parameters: K: The type of keys in the map. V: The type of values in the map. Parameters: initialState?: MapOrEntries - The initial state of the map as a Map or an array of key-value pairs (optional). Returns: UseMapReturn - A tuple containing the map state and actions to interact with the map. Type Aliases: MapOrEntries: Map | [K, V][] Description: Represents the type for either a Map or an array of key-value pairs. Type parameters: K: The type of keys in the map. V: The type of values in the map. UseMapActions: Object Description: Represents the actions available to interact with the map state. Type parameters: K: The type of keys in the map. V: The type of values in the map. ``` -------------------------------- ### React Hook useDebounceCallback Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-debounce-callback Demonstrates how to import and use the `useDebounceCallback` hook within a React component to debounce state updates from an input field, preventing excessive re-renders or function calls. ```javascript import { useState } from 'react' import { useDebounceCallback } from 'usehooks-ts' export default function Component() { const [value, setValue] = useState('') const debounced = useDebounceCallback(setValue, 500) return (

Debounced value: {value}

debounced(event.target.value)} />
) } ``` -------------------------------- ### React Hook: useDarkMode Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-dark-mode Demonstrates how to import and use the `useDarkMode` hook within a React component to display the current theme and provide buttons to toggle, enable, and disable dark mode. ```TypeScript import { useDarkMode } from 'usehooks-ts' export default function Component() { const { isDarkMode, toggle, enable, disable } = useDarkMode() return (

Current theme: {isDarkMode ? 'dark' : 'light'}

) } ``` -------------------------------- ### useScreen Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-screen Detailed API documentation for the `useScreen` custom hook, outlining its two overloaded signatures, their respective parameters, return types, and the `UseScreenOptions` type alias used for customizing the hook's behavior, including initialization and debouncing. ```APIDOC useScreen(options: UseScreenOptions): Screen | undefined Description: Custom hook that tracks the screen dimensions and properties. Parameters: options: UseScreenOptions - The options for customizing the behavior of the hook (optional). Returns: Screen | undefined - The current Screen object representing the screen dimensions and properties, or undefined if not available. useScreen(options?: Partial>): Screen Description: Custom hook that tracks the screen dimensions and properties. Parameters: options?: Partial> - The options for customizing the behavior of the hook (optional). Returns: Screen - The current Screen object representing the screen dimensions and properties, or undefined if not available. Type alias: UseScreenOptions Description: The hooks options. Type parameters: InitializeWithValue extends boolean | undefined - If true (default), the hook will initialize reading the screen dimensions. In SSR, you should set it to false, returning undefined initially. Properties: debounceDelay?: number - The delay in milliseconds before the state is updated (disabled by default for retro-compatibility). Default: undefined initializeWithValue: InitializeWithValue - If true (default), the hook will initialize reading the screen dimensions. In SSR, you should set it to false, returning undefined initially. Default: true ``` -------------------------------- ### Example Usage of useIsomorphicLayoutEffect in a Component Source: https://usehooks-ts.com/introduction/react-hook/use-isomorphic-layout-effect This snippet demonstrates how to import and integrate the `useIsomorphicLayoutEffect` hook into a functional React component. It illustrates the hook's behavior by logging a message that indicates whether it's acting as `useLayoutEffect` (browser) or `useEffect` (SSR). ```TypeScript import { useIsomorphicLayoutEffect } from 'usehooks-ts' export default function Component() { useIsomorphicLayoutEffect(() => { console.log( "In the browser, I'm an `useLayoutEffect`, but in SSR, I'm an `useEffect`.", ) }, []) return

Hello, world

} ``` -------------------------------- ### API Reference for useClickAnyWhere Hook Source: https://usehooks-ts.com/introduction/react-hook/use-click-any-where Detailed API documentation for the `useClickAnyWhere` hook, outlining its parameters, their types, descriptions, and the return type. It specifies the expected handler function signature. ```APIDOC useClickAnyWhere(handler: (event: MouseEvent) => void): void Description: Custom hook that handles click events anywhere on the document. Parameters: handler: Type: (event: MouseEvent) => void Description: The function to be called when a click event is detected anywhere on the document. Returns: void ``` -------------------------------- ### useScript Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-script Detailed API documentation for the `useScript` hook, including its parameters, return values, and related type definitions (`UseScriptOptions` and `UseScriptStatus`). ```APIDOC useScript(src: string | null, options?: UseScriptOptions): UseScriptStatus src: The source URL of the script to load. Set to `null` or omit to prevent loading (optional). options?: Additional options for controlling script loading (optional). Returns: UseScriptStatus - The status of the script loading, which can be one of 'idle', 'loading', 'ready', or 'error'. Type alias UseScriptOptions: Object Hook options. id?: string - Script's `id` (optional). removeOnUnmount?: boolean - If `true`, removes the script from the DOM when the component unmounts (optional). shouldPreventLoad?: boolean - If `true`, prevents the script from being loaded (optional). Type alias UseScriptStatus: "idle" | "loading" | "ready" | "error" Script loading status. ``` -------------------------------- ### Use useIsClient Hook in React Component Source: https://usehooks-ts.com/introduction/react-hook/use-is-client This snippet demonstrates how to import and utilize the `useIsClient` hook within a React functional component. It shows a simple conditional rendering based on whether the code is running on the client or server, providing a practical example of its usage. ```TypeScript import { useIsClient } from 'usehooks-ts' export default function Component() { const isClient = useIsClient() return
{isClient ? 'Client' : 'server'}
} ``` -------------------------------- ### React useSessionStorage Hook Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-session-storage Demonstrates how to use the `useSessionStorage` hook to manage a counter value that persists in session storage. It shows how to initialize the hook, update the stored value, and remove it, with interactive buttons for incrementing, decrementing, and resetting the count. ```TypeScript import { useSessionStorage } from 'usehooks-ts' export default function Component() { const [value, setValue, removeValue] = useSessionStorage('test-key', 0) return (

Count: {value}

) } ``` -------------------------------- ### Implement useWindowSize React Hook Source: https://usehooks-ts.com/introduction/react-hook/use-window-size Provides a React hook to track window dimensions, handling both SSR and CSR scenarios. It includes options for initial value setting and debouncing resize events for performance optimization. ```TypeScript import { useState } from 'react' import { useDebounceCallback, useEventListener, useIsomorphicLayoutEffect, } from 'usehooks-ts' type WindowSize = { width: T height: T } type UseWindowSizeOptions = { initializeWithValue: InitializeWithValue debounceDelay?: number } const IS_SERVER = typeof window === 'undefined' // SSR version of useWindowSize. export function useWindowSize(options: UseWindowSizeOptions): WindowSize // CSR version of useWindowSize. export function useWindowSize( options?: Partial>, ): WindowSize export function useWindowSize( options: Partial> = {}, ): WindowSize | WindowSize { let { initializeWithValue = true } = options if (IS_SERVER) { initializeWithValue = false } const [windowSize, setWindowSize] = useState(() => { if (initializeWithValue) { return { width: window.innerWidth, height: window.innerHeight, } } return { width: undefined, height: undefined, } }) const debouncedSetWindowSize = useDebounceCallback( setWindowSize, options.debounceDelay, ) function handleSize() { const setSize = options.debounceDelay ? debouncedSetWindowSize : setWindowSize setSize({ width: window.innerWidth, height: window.innerHeight, }) } useEventListener('resize', handleSize) // Set size at the first client-side load useIsomorphicLayoutEffect(() => { handleSize() }, []) return windowSize } ``` -------------------------------- ### useOnClickOutside Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-on-click-outside Detailed API documentation for the `useOnClickOutside` hook, outlining its signature, type parameters, parameters with their types, default values, and descriptions, as well as its return type and supported event types. ```APIDOC useOnClickOutside(ref, handler, eventType?, eventListenerOptions?): void Description: Custom hook that handles clicks outside a specified element. Type parameters: T: extends HTMLElement = HTMLElement Description: The type of the element's reference. Parameters: ref: RefObject | RefObject[] | undefined Default value: undefined Description: The React ref object(s) representing the element(s) to watch for outside clicks. handler: (event: MouseEvent | FocusEvent | TouchEvent) => void Default value: undefined Description: The callback function to be executed when a click outside the element occurs. eventType?: EventType Default value: 'mousedown' Description: The mouse event type to listen for (optional, default is 'mousedown'). eventListenerOptions?: AddEventListenerOptions Default value: {} Description: The options object to be passed to the `addEventListener` method (optional). Returns: void Type aliases: EventType: "mousedown" | "mouseup" | "touchstart" | "touchend" | "focusin" | "focusout" Description: Supported event types. ``` -------------------------------- ### useWindowSize Hook API Definition Source: https://usehooks-ts.com/introduction/react-hook/use-window-size Defines the overloaded signatures, parameters, and return types for the `useWindowSize` React hook, including its supporting type definitions `WindowSize` and `UseWindowSizeOptions`. ```APIDOC useWindowSize(options: UseWindowSizeOptions): WindowSize useWindowSize(options?: Partial>): WindowSize useWindowSize(options: Partial> = {}): WindowSize | WindowSize Types: WindowSize: width: T height: T UseWindowSizeOptions: initializeWithValue: InitializeWithValue (boolean) - If true, initializes with current window size. Defaults to true. debounceDelay?: number (optional) - Delay in milliseconds to debounce resize events. ``` -------------------------------- ### Auto Lock Scroll on Component Mount with useScrollLock Source: https://usehooks-ts.com/introduction/react-hook/use-scroll-lock This example demonstrates how to automatically lock the scroll of the `body` element when a component, such as a modal, mounts. By simply calling `useScrollLock()` without arguments, the hook defaults to locking the scroll of `document.body`, preventing background scrolling. ```typescript import { useScrollLock } from 'usehooks-ts' // Example 1: Auto lock the scroll of the body element when the modal mounts export default function Modal() { useScrollLock() return
Modal
} ``` -------------------------------- ### Example Usage of useTimeout Hook in React Source: https://usehooks-ts.com/introduction/react-hook/use-timeout This snippet demonstrates how to use the `useTimeout` hook within a React component to hide content after a specified delay. It utilizes `useState` to manage visibility and `useTimeout` to trigger the `hide` function after 5000 milliseconds, showcasing a common application of the hook. ```typescript import { useState } from 'react' import { useTimeout } from 'usehooks-ts' export default function Component() { const [visible, setVisible] = useState(true) const hide = () => { setVisible(false) } useTimeout(hide, 5000) return (

{visible ? "I'm visible for 5000ms" : 'You can no longer see this content'}

) } ``` -------------------------------- ### useTimeout Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-timeout Detailed API documentation for the `useTimeout` hook, outlining its parameters (`callback` and `delay`) and return type. It explains the purpose of each parameter and the overall functionality of the hook, clarifying how to interact with it. ```APIDOC â–¸ useTimeout(callback, delay): void Custom hook that handles timeouts in React components using the setTimeout API. Parameters: - callback: () => void The function to be executed when the timeout elapses. - delay: null | number The duration (in milliseconds) for the timeout. Set to null to clear the timeout. Returns: void This hook does not return anything. ``` -------------------------------- ### React Hook: useIsMounted Usage Example Source: https://usehooks-ts.com/introduction/react-hook/use-is-mounted Demonstrates how to use the `useIsMounted` hook within a React component to prevent state updates on unmounted components, simulating an asynchronous API call. It shows a parent component toggling the visibility of a child component that uses `useIsMounted` to safely update its state. ```TypeScript import { useEffect, useState } from 'react' import { useIsMounted } from 'usehooks-ts' const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)) function Child() { const [data, setData] = useState('loading') const isMounted = useIsMounted() // simulate an api call and update state useEffect(() => { void delay(3000).then(() => { if (isMounted()) setData('OK') }) }, [isMounted]) return

{data}

} export default function Component() { const [isVisible, setVisible] = useState(false) const toggleVisibility = () => { setVisible(state => !state) } return ( <> {isVisible && } ) } ``` -------------------------------- ### useMap React Hook TypeScript Implementation Source: https://usehooks-ts.com/introduction/react-hook/use-map Provides the full TypeScript implementation of the `useMap` React hook, demonstrating how to manage a Map state with utility actions like set, setAll, remove, and reset, using React's `useState` and `useCallback` hooks. ```typescript import { useCallback, useState } from 'react' type MapOrEntries = Map | [K, V][] type UseMapActions = { set: (key: K, value: V) => void setAll: (entries: MapOrEntries) => void remove: (key: K) => void reset: Map['clear'] } type UseMapReturn = [ Omit, 'set' | 'clear' | 'delete'>, UseMapActions, ] export function useMap( initialState: MapOrEntries = new Map(), ): UseMapReturn { const [map, setMap] = useState(new Map(initialState)) const actions: UseMapActions = { set: useCallback((key, value) => { setMap(prev => { const copy = new Map(prev) copy.set(key, value) return copy }) }, []), setAll: useCallback(entries => { setMap(() => new Map(entries)) }, []), remove: useCallback(key => { setMap(prev => { const copy = new Map(prev) copy.delete(key) return copy }) }, []), reset: useCallback(() => { setMap(() => new Map()) }, []), } return [map, actions] } ``` -------------------------------- ### API Reference for useIsomorphicLayoutEffect Hook Source: https://usehooks-ts.com/introduction/react-hook/use-isomorphic-layout-effect This section provides the formal API documentation for the `useIsomorphicLayoutEffect` hook. It details the `effect` callback function and optional `deps` dependency array parameters, along with the `void` return type, clarifying its signature and purpose. ```APIDOC useIsomorphicLayoutEffect(effect: EffectCallback, deps?: DependencyList): void effect: EffectCallback - The effect function to be executed. deps?: DependencyList - Optional dependency array for the effect. ``` -------------------------------- ### React Component Example using useDebounceValue Hook Source: https://usehooks-ts.com/introduction/react-hook/use-debounce-value This code snippet illustrates how to integrate and utilize the `useDebounceValue` hook within a React functional component. It demonstrates how to manage a debounced state, update it via an input field, and display the debounced value, which updates only after a specified delay. ```typescript import { useDebounceValue } from 'usehooks-ts' export default function Component({ defaultValue = 'John' }) { const [debouncedValue, setValue] = useDebounceValue(defaultValue, 500) return (

Debounced value: {debouncedValue}

setValue(event.target.value)} />
) } ``` -------------------------------- ### useBoolean Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-boolean This section provides detailed API documentation for the `useBoolean` hook, outlining its parameters, return type, and the structure of the `UseBooleanReturn` object. It specifies the expected input for `defaultValue` and describes each utility function provided by the hook. ```APIDOC useBoolean(defaultValue?): UseBooleanReturn Description: Custom hook that handles boolean state with useful utility functions. Parameters: defaultValue?: boolean (Default: false) Description: The initial value for the boolean state. Returns: UseBooleanReturn Description: An object containing the boolean state value and utility functions to manipulate the state. Throws: Will throw an error if `defaultValue` is an invalid boolean value. Type alias: UseBooleanReturn: Object Description: The useBoolean return type. Type declaration: setFalse: () => void Description: Function to set the boolean state to `false`. setTrue: () => void Description: Function to set the boolean state to `true`. setValue: Dispatch> Description: Function to set the boolean state directly. toggle: () => void Description: Function to toggle the boolean state. value: boolean Description: The current boolean state value. ``` -------------------------------- ### useCountdown Hook API Reference Source: https://usehooks-ts.com/introduction/react-hook/use-countdown This section provides the detailed API documentation for the `useCountdown` hook, including its parameters, return types, and associated type aliases. It defines the `CountdownControllers` for managing the countdown and `CountdownOptions` for configuring its behavior. ```APIDOC ▸ useCountdown(countdownOptions): [number, CountdownControllers] Custom hook that manages countdown. Parameters: countdownOptions: CountdownOptions - The countdown's options. Returns: [number, CountdownControllers] - An array containing the countdown's count and its controllers. Ƭ CountdownControllers: Object The countdown's controllers. Type declaration: resetCountdown: () => void - Reset the countdown. startCountdown: () => void - Start the countdown. stopCountdown: () => void - Stop the countdown. Ƭ CountdownOptions: Object The countdown's options. Type declaration: countStart: number - The countdown's starting number, initial value of the returned number. countStop?: number - The countdown's stopping number. Pass -Infinity to decrease forever. Default ts 0 intervalMs?: number - The countdown's interval, in milliseconds. Default ts 1000 isIncrement?: boolean - True if the countdown is increment. Default ts false ```