### Install @react-hookz/web with yarn
Source: https://github.com/react-hookz/web/blob/master/README.md
Use this command to install the library using yarn.
```shell
yarn add @react-hookz/web
```
--------------------------------
### Install @react-hookz/web with npm
Source: https://github.com/react-hookz/web/blob/master/README.md
Use this command to install the library using npm.
```shell
npm i @react-hookz/web
```
--------------------------------
### Running Storybook Watch
Source: https://github.com/react-hookz/web/blob/master/CONTRIBUTING.md
Start Storybook in watch mode to preview your hook documentation locally.
```shell
yarn storybook:watch
```
--------------------------------
### useList Example for Todo List
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Illustrates managing a list of todos using the useList hook, including adding, updating, and deleting items.
```typescript
function TodoList() {
const [todos, actions] = useList([
{ id: 1, text: 'Learn hooks', done: false },
]);
return (
);
}
```
--------------------------------
### useCustomCompareEffect Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/LIFECYCLE_HOOKS.md
This example demonstrates how to use useCustomCompareEffect with a custom dependency comparator. The effect will only re-run if the stringified previous and next config objects are different, preventing unnecessary re-renders.
```typescript
function ConfigComponent({ config }) {
useCustomCompareEffect(
() => {
console.log('Config updated');
applyConfig(config);
},
[config],
(prev, next) => {
// Deep comparison of config objects
return JSON.stringify(prev[0]) === JSON.stringify(next[0]);
}
);
return
Config applied
;
}
```
--------------------------------
### Example Usage of useQueue Hook
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Demonstrates how to use the useQueue hook to manage a list of tasks, allowing users to add, process, and clear tasks.
```typescript
function TaskProcessor() {
const [tasks, actions] = useQueue(['task1', 'task2']);
const processNext = () => {
const task = actions.remove();
if (task) {
console.log('Processing', task);
}
};
return (
Queue size: {tasks.length}
);
}
```
--------------------------------
### Example Usage of useAsyncAbortable
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
Demonstrates how to use the useAsyncAbortable hook to fetch data with cancellation support. It shows how to execute the search, display loading states, and cancel the request.
```typescript
function SearchWithCancel({ query }) {
const [results, actions, meta] = useAsyncAbortable(
async (signal: AbortSignal, searchTerm: string) => {
const response = await fetch(`/api/search?q=${searchTerm}`, {
signal,
});
return response.json();
}
);
useEffect(() => {
if (query) {
actions.execute(query);
}
}, [query, actions]);
return (
{results.status === 'loading' && (
<>
Searching...
>
)}
{results.status === 'success' && (
{results.result.map((item) => (
{item.name}
))}
)}
);
}
```
--------------------------------
### useMap Hook Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Demonstrates how to use the useMap hook to manage a Map state with automatic re-renders on mutations. It allows adding, deleting, and displaying entries.
```typescript
function CacheViewer() {
const cache = useMap([['key1', 'value1']]);
return (
);
}
```
--------------------------------
### useDebouncedState Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Demonstrates how to use useDebouncedState to debounce search input, fetching results only after the user stops typing for a specified delay.
```typescript
function SearchInput() {
const [searchTerm, setSearchTerm] = useDebouncedState('', 300);
const [results, setResults] = useState([]);
useEffect(() => {
if (searchTerm) {
fetch(`/api/search?q=${searchTerm}`)
.then(r => r.json())
.then(setResults);
}
}, [searchTerm]);
return (
);
}
```
--------------------------------
### useDeepCompareMemo Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Illustrates using useDeepCompareMemo to memoize the result of an expensive computation based on a configuration object. It ensures recomputation only when the configuration's content deeply changes, not just its reference.
```typescript
function ComplexComponent({ config }) {
const memoizedValue = useDeepCompareMemo(
() => {
return expensiveComputation(config);
},
[config] // Even if config object reference changes, equality check detects same content
);
return
{memoizedValue}
;
}
```
--------------------------------
### Control Video Playback with Visibility
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
This example demonstrates how to use the useDocumentVisibility hook to control video playback. It pauses the video when the document is hidden and resumes it when visible.
```typescript
function VideoPlayer() {
const visibility = useDocumentVisibility();
useEffect(() => {
const video = document.querySelector('video');
if (video) {
if (visibility === 'hidden') {
video.pause();
} else if (visibility === 'visible') {
video.play();
}
}
}, [visibility]);
return ;
}
```
--------------------------------
### useFunctionalState Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Demonstrates using useFunctionalState to manage form data and access the latest state within callbacks like validation.
```typescript
function FormWithValidation() {
const [getFormData, setFormData] = useFunctionalState({
name: '',
email: '',
});
const validateForm = useCallback(() => {
const data = getFormData(); // Always gets current state
return data.name.length > 0 && data.email.includes('@');
}, [getFormData]);
return (
);
}
```
--------------------------------
### Control Audio Recording with Microphone Permission
Source: https://github.com/react-hookz/web/blob/master/_autodocs/NAVIGATOR_AND_MISC_HOOKS.md
This example demonstrates how to disable or enable an audio recording button based on the microphone permission status. It prevents recording if the microphone access is not granted.
```typescript
function AudioRecorder() {
const micPermission = usePermission('microphone');
const startRecording = async () => {
if (micPermission?.state !== 'granted') {
console.log('Microphone not allowed');
return;
}
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
const recorder = new MediaRecorder(stream);
recorder.start();
};
return (
);
}
```
--------------------------------
### useLocalStorageValue Hook Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
Demonstrates how to use the useLocalStorageValue hook to manage user preferences like theme and font size. It includes setting, updating, and removing values from localStorage.
```typescript
function UserPreferences() {
const preferences = useLocalStorageValue('userPrefs', {
defaultValue: { theme: 'light', fontSize: 14 },
});
return (
);
}
```
--------------------------------
### useHookableRef
Source: https://github.com/react-hookz/web/blob/master/README.md
Like `useRef` but it is possible to define handlers for getting and setting the value.
```APIDOC
## useHookableRef
### Description
Like `useRef` but it is possible to define handlers for getting and setting the value.
### Usage
```javascript
const hookableRef = useHookableRef(initialValue, { get, set });
```
### Parameters
- `initialValue` (*): The initial value for the ref.
- `handlers` (object): An object with optional `get` and `set` handlers.
- `get` (function): A function called when the ref's value is accessed.
- `set` (function): A function called when the ref's value is set.
### Returns
- `hookableRef` (object): An object with a `current` property representing the ref.
```
--------------------------------
### useKeyboardEvent Hook Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/DOM_AND_REF_HOOKS.md
Demonstrates listening for 'Escape' to close a modal, a custom Ctrl+K combination to toggle visibility, and 'Enter' key press within an input field targeting a specific ref. Includes dependency tracking for the input value.
```typescript
function SearchWithKeyboard() {
const [isOpen, setIsOpen] = useState(false);
const [input, setInput] = useState('');
// Listen for Escape to close
useKeyboardEvent('Escape', () => {
setIsOpen(false);
});
// Listen for custom modifier combination
useKeyboardEvent(
(event) => event.ctrlKey && event.key === 'k',
() => {
setIsOpen(!isOpen);
}
);
// Enter key in input
const inputRef = useRef(null);
useKeyboardEvent(
'Enter',
() => {
console.log('Search:', input);
},
[input],
{ target: inputRef }
);
return (
{isOpen && (
setInput(e.target.value)}
placeholder="Type to search..."
/>
)}
);
}
```
--------------------------------
### useVibrate Hook Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/NAVIGATOR_AND_MISC_HOOKS.md
Demonstrates how to use the useVibrate hook to control vibration patterns based on user interactions or application state. Vibration stops on component unmount. Pass false/null to disable without unmounting.
```typescript
function HapticButton() {
const [pattern, setPattern] = useState(null);
const vibrate = (p: number | number[]) => {
setPattern(p);
// Pattern will vibrate once then stop
};
useVibrate(pattern);
return (
);
}
function FormSubmit() {
const [state, actions] = useAsync(submitForm);
useVibrate(
state.status === 'success' ? [100, 50, 100, 50, 100] : null
);
return (
);
}
```
--------------------------------
### Example Usage of useCounter Hook
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Demonstrates how to use the useCounter hook in a React component to manage a rating system with increment, decrement, reset, and set actions.
```typescript
function RatingComponent() {
const [rating, actions] = useCounter(0, 5, 0);
return (
Rating: {rating}/5
);
}
```
--------------------------------
### Example Usage of useRafState Hook
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Illustrates using useRafState to update a UI element's position based on mouse movement, ensuring smooth transitions by deferring state updates to the next animation frame.
```typescript
function SmoothedAnimation() {
const [x, setX] = useRafState(0);
const handleMouseMove = (e) => {
setX(e.clientX); // Applied in next RAF
};
useEventListener(window, 'mousemove', handleMouseMove);
return
Moving
;
}
```
--------------------------------
### Use useEventListener Hook for Window Events
Source: https://github.com/react-hookz/web/blob/master/_autodocs/DOM_AND_REF_HOOKS.md
Attach event listeners to the window object with automatic cleanup. This example demonstrates listening for scroll and resize events.
```typescript
function ScrollListener() {
const [scrollY, setScrollY] = useState(0);
useEventListener(window, 'scroll', (e) => {
setScrollY(window.scrollY);
});
useEventListener(
window,
'resize',
() => {
console.log('Window resized');
},
{ passive: true }
);
return
Scroll Y: {scrollY}px
;
}
```
--------------------------------
### useSyncedRef Example for Debounced Search
Source: https://github.com/react-hookz/web/blob/master/_autodocs/DOM_AND_REF_HOOKS.md
Demonstrates using useSyncedRef to ensure a debounced callback always accesses the latest input value without needing to include it in the dependency array.
```typescript
function DebounceExample() {
const [text, setText] = useState('');
const textRef = useSyncedRef(text);
const debouncedSearch = useDebouncedCallback(
() => {
// textRef.current always has latest text
performSearch(textRef.current);
},
[], // Empty deps possible because textRef has current value
300
);
return (
{
setText(e.target.value);
debouncedSearch();
}}
/>
);
}
```
--------------------------------
### useMediatedState Hook Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Illustrates the use of useMediatedState to manage state with a mediator function for validation or normalization. This example ensures the age is kept within a valid range.
```typescript
function AgeInput() {
const [age, setAge] = useMediatedState(0, (newAge) => {
// Ensure age is between 0 and 120
return Math.max(0, Math.min(120, newAge));
});
return (
setAge(Number(e.target.value))}
/>
Age: {age}
);
}
```
--------------------------------
### Responsive Layout with useMediaQuery
Source: https://github.com/react-hookz/web/blob/master/_autodocs/README.md
Adapt UI components based on screen size using `useMediaQuery`. Pass a media query string to determine responsiveness.
```typescript
const isMobile = useMediaQuery('(max-width: 768px)');
return isMobile ? : ;
```
--------------------------------
### useValidator Hook Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
This example demonstrates how to use the useValidator hook with an asynchronous validator to validate an email input. It shows how to handle state for the input, trigger validation on dependency changes, and display validation results. The revalidate function can be used to manually trigger validation.
```typescript
function EmailValidator() {
const [email, setEmail] = useState('');
const [validity, revalidate] = useValidator(
async (done) => {
const response = await fetch(`/api/validate-email?email=${email}`);
const isValid = await response.json();
done({ isValid, email });
},
[email]
);
return (
);
}
```
--------------------------------
### Setting Up Remote Upstream
Source: https://github.com/react-hookz/web/blob/master/CONTRIBUTING.md
Configure your local repository to easily pull changes from the original upstream repository.
```shell
git remote add upstream https://github.com/react-hookz/web.git
git fetch upstream
git branch --set-upstream-to=upstream/master master
```
--------------------------------
### useRenderCount
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Tracks how many times a component has rendered, including the first render. It returns an incremental render count starting from 1.
```APIDOC
## useRenderCount
### Description
Tracks how many times a component has rendered, including the first render.
### Signature
```typescript
function useRenderCount(): number
```
### Parameters
This hook does not accept any parameters.
### Return Type
`number` - Incremental render count starting from 1.
### Behavior
- Increments on every render
- Useful for debugging or instrumentation
- Minimal performance impact
### Example
```typescript
function DebugComponent() {
const renderCount = useRenderCount();
return
Rendered {renderCount} times
;
}
```
```
--------------------------------
### Responsive Modal with useMediaQuery and useClickOutside
Source: https://github.com/react-hookz/web/blob/master/_autodocs/QUICK_REFERENCE.md
Creates a modal component that adapts its styling based on screen size and closes when a click occurs outside of it. Uses `useMediaQuery` for responsiveness and `useClickOutside` for dismissal.
```typescript
function Modal() {
const modalRef = useRef(null);
const [open, setOpen] = useState(false);
const isMobile = useMediaQuery('(max-width: 768px)');
useClickOutside(modalRef, () => setOpen(false));
if (!open) return null;
return (
{/* Modal content */}
);
}
```
--------------------------------
### Creating a New Hook
Source: https://github.com/react-hookz/web/blob/master/CONTRIBUTING.md
Use this command to generate the basic file structure for a new hook.
```shell
yarn new-hook myAwesomeHook
```
--------------------------------
### useCustomCompareMemo
Source: https://github.com/react-hookz/web/blob/master/README.md
Like `useMemo` but uses provided comparator function to validate dependency changes.
```APIDOC
## useCustomCompareMemo
### Description
Like `useMemo` but uses provided comparator function to validate dependency changes.
### Usage
```javascript
const memoizedValue = useCustomCompareMemo(createValue, dependencies, comparator);
```
### Parameters
- `createValue` (function): Function to compute the memoized value.
- `dependencies` (Array): An array of dependencies.
- `comparator` (function): A function that compares two dependency arrays.
### Returns
- The memoized value.
```
--------------------------------
### Use useEventListener Hook with a Ref
Source: https://github.com/react-hookz/web/blob/master/_autodocs/DOM_AND_REF_HOOKS.md
Attach an event listener to a specific DOM element referenced by a React ref. This example shows listening for a click event on a div.
```typescript
function RefExample() {
const ref = useRef(null);
useEventListener(ref, 'click', () => {
console.log('Element clicked');
});
return
Click me
;
}
```
--------------------------------
### useFirstMountState
Source: https://github.com/react-hookz/web/blob/master/_autodocs/LIFECYCLE_HOOKS.md
Returns a boolean that is `true` only during the first render. It does not cause re-renders and is perfect for initializing state with expensive computations only once. It is also SSR-safe.
```APIDOC
## useFirstMountState
### Description
Returns a boolean that is `true` only during the first render.
### Signature
```typescript
function useFirstMountState(): boolean
```
### Return Type
`boolean` - `true` on first render, `false` on all subsequent renders.
### Behavior
- Does not cause re-renders
- Perfect for initializing state with expensive computations only once
- SSR-safe
### Example
```typescript
function Component({ initialData }) {
const isFirstMount = useFirstMountState();
const [data, setData] = useState(null);
useEffect(() => {
if (isFirstMount) {
setData(initialData);
}
}, []);
return
{data}
;
}
```
```
--------------------------------
### Import Hooks from Package Root
Source: https://github.com/react-hookz/web/blob/master/_autodocs/QUICK_REFERENCE.md
Demonstrates the standard way to import any hook from the root of the @react-hookz/web package.
```typescript
import { hookName } from '@react-hookz/web';
```
--------------------------------
### Importing useMountEffect Hook
Source: https://github.com/react-hookz/web/blob/master/_autodocs/00_START_HERE.md
Demonstrates two ways to import the `useMountEffect` hook from the `@react-hookz/web` library. The root import is recommended for general use, while direct module import can aid tree-shaking in certain bundlers.
```typescript
// Import from root (recommended)
import { useMountEffect } from '@react-hookz/web';
// Or direct module import (for tree-shaking in some bundlers)
import { useMountEffect } from '@react-hookz/web/useMountEffect/index.js';
// Both are equivalent
```
--------------------------------
### Track Element Dimensions with useMeasure
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
Use `useMeasure` to get the width and height of an element. Attach the returned ref to the target element. The hook automatically updates dimensions on resize.
```typescript
function useMeasure(
enabled?: boolean,
): [Measures | undefined, RefObject]
type Measures = {
width: number;
height: number;
}
```
```typescript
function ResponsiveContainer() {
const [measures, ref] = useMeasure();
return (
);
}
```
--------------------------------
### useMediaQuery
Source: https://github.com/react-hookz/web/blob/master/README.md
Tracks the state of a CSS media query.
```APIDOC
## useMediaQuery
### Description
Tracks the state of a CSS media query.
### Usage
```javascript
const matches = useMediaQuery(query);
```
### Parameters
- `query` (string): The media query string (e.g., '(min-width: 768px)').
### Returns
- `matches` (boolean): True if the media query currently matches.
```
--------------------------------
### Detect First Mount with useFirstMountState
Source: https://github.com/react-hookz/web/blob/master/_autodocs/LIFECYCLE_HOOKS.md
Use this hook to get a boolean that is true only during the first render of a component. It does not cause re-renders and is SSR-safe, making it ideal for initializing state with expensive computations once.
```typescript
function Component({ initialData }) {
const isFirstMount = useFirstMountState();
const [data, setData] = useState(null);
useEffect(() => {
if (isFirstMount) {
setData(initialData);
}
}, []);
return
{data}
;
}
```
--------------------------------
### Import Hooks from @react-hookz/web
Source: https://github.com/react-hookz/web/blob/master/_autodocs/API_OVERVIEW.md
Demonstrates two ways to import hooks: from the root package or directly from individual module paths. Both methods are equivalent with tree-shaking enabled bundlers.
```typescript
import { useMountEffect } from '@react-hookz/web';
```
```typescript
import { useMountEffect } from '@react-hookz/web/useMountEffect/index.js';
```
--------------------------------
### useControlledRerenderState Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Use `useControlledRerenderState` to manage component state without triggering re-renders on every update. State changes are stored in a ref, and re-renders are explicitly controlled, which is useful for performance optimization.
```typescript
function OptimizedForm() {
const [formState, setFormState] = useControlledRerenderState({
name: '',
email: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormState(
(prev) => ({ ...prev, [name]: value }),
false // Don't re-render on every keystroke
);
};
const handleSubmit = async (e) => {
e.preventDefault();
await saveForm(formState);
// Optionally trigger re-render after submit
setFormState((prev) => prev, true);
};
return (
);
}
```
--------------------------------
### useWindowSize
Source: https://github.com/react-hookz/web/blob/master/README.md
Tracks the inner dimensions of the browser window.
```APIDOC
## useWindowSize
### Description
Tracks the inner dimensions of the browser window.
### Usage
```javascript
const { width, height } = useWindowSize();
```
### Returns
- `width` (number): The current inner width of the browser window.
- `height` (number): The current inner height of the browser window.
```
--------------------------------
### Use Window Size in React Component
Source: https://github.com/react-hookz/web/blob/master/_autodocs/DOM_AND_REF_HOOKS.md
Use this hook to get the current window dimensions and conditionally render components based on screen size. It initializes with the current window size by default.
```typescript
function ResponsiveComponent() {
const windowSize = useWindowSize();
return (
);
}
```
--------------------------------
### useDeepCompareMemo
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
A memoization hook that compares dependencies using deep equality instead of reference equality, similar to `useMemo` but more robust for complex objects and arrays.
```APIDOC
## useDeepCompareMemo
Like `useMemo` but validates dependency changes using deep equality instead of reference equality.
### Signature
```typescript
function useDeepCompareMemo(
factory: () => T,
deps: Deps,
): T
```
### Parameters
#### Parameters Table
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| factory | `() => T` | yes | Function computing the memoized value |
| deps | `Deps` | yes | Dependency array |
### Return Type
`T`
Memoized value, recomputed only when dependencies deeply change.
### Behavior
- Uses `@ver0/deep-equal` for dependency comparison
- More expensive than reference checks but handles object/array restructuring
- Useful when dependencies are complex objects recreated each render
### Example
```typescript
function ComplexComponent({ config }) {
const memoizedValue = useDeepCompareMemo(
() => {
return expensiveComputation(config);
},
[config] // Even if config object reference changes, equality check detects same content
);
return
{memoizedValue}
;
}
```
```
--------------------------------
### Format Commit Messages with Yarn Commit
Source: https://github.com/react-hookz/web/blob/master/CONTRIBUTING.md
Use this script to properly format commit messages according to conventional commit standards. It guides you through prompts to ensure all necessary parts of a commit message are included.
```shell
git add .
yarn commit
```
--------------------------------
### useMediaQuery
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
Tracks CSS media query match state, automatically updating when screen size or media conditions change. It returns a boolean indicating if the query matches, or undefined if not yet initialized.
```APIDOC
## useMediaQuery
Tracks CSS media query match state, automatically updating when screen size or media conditions change.
### Signature:
```typescript
function useMediaQuery(
query: string,
options?: UseMediaQueryOptions,
): boolean | undefined
type UseMediaQueryOptions = {
initializeWithValue?: boolean;
}
```
### Parameters:
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| query | `string` | yes | — | CSS media query string |
| options | `UseMediaQueryOptions` | no | — | Hook options |
### Options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| initializeWithValue | `boolean` | `true` | Initialize with query match on first render |
### Return Type:
`boolean | undefined`
`true` if query matches, `false` if not, `undefined` if not yet initialized.
### Behavior:
- SSR-safe: returns undefined on server (initializeWithValue=false during SSR)
- Pooled listeners: multiple hooks with same query share listener
- Automatically handles media query changes
### Example:
```typescript
function ResponsiveLayout() {
const isMobile = useMediaQuery('(max-width: 768px)');
const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
if (isMobile === undefined) return null;
return (
{isMobile ? : }
);
}
```
```
--------------------------------
### useAsync
Source: https://github.com/react-hookz/web/blob/master/README.md
Executes provided async function and tracks its results and errors.
```APIDOC
## useAsync
### Description
Executes provided async function and tracks its results and errors.
### Usage
```javascript
const { execute, loading, data, error } = useAsync(asyncFunction, immediate);
```
### Parameters
- `asyncFunction` (function): The async function to execute.
- `immediate` (boolean, optional): If true, executes the function immediately on mount.
### Returns
- `execute` (function): Function to manually trigger the async function.
- `loading` (boolean): Indicates if the async function is currently executing.
- `data` (*): The result of the async function.
- `error` (Error): The error object if the async function failed.
```
--------------------------------
### Monitor CSS Media Queries with useMediaQuery
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
Use `useMediaQuery` to get the boolean state of a CSS media query. It's SSR-safe and automatically updates when media conditions change. Set `initializeWithValue` to `false` for SSR.
```typescript
function useMediaQuery(
query: string,
options?: UseMediaQueryOptions,
): boolean | undefined
type UseMediaQueryOptions = {
initializeWithValue?: boolean;
}
```
```typescript
function ResponsiveLayout() {
const isMobile = useMediaQuery('(max-width: 768px)');
const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
if (isMobile === undefined) return null;
return (
{isMobile ? : }
);
}
```
--------------------------------
### UseMediaQueryOptions Type
Source: https://github.com/react-hookz/web/blob/master/_autodocs/TYPES_REFERENCE.md
Configuration options for the `useMediaQuery` hook. Controls whether the hook initializes with a value.
```typescript
type UseMediaQueryOptions = {
initializeWithValue?: boolean;
};
```
--------------------------------
### useDebouncedCallback Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/CALLBACK_HOOKS.md
Creates a debounced version of a callback function. Useful for handling frequent events like typing or window resizing. The scheduled execution clears when dependencies change and pending execution is canceled on component unmount.
```typescript
function SearchComponent() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const handleSearch = useDebouncedCallback(
async (searchTerm: string) => {
const response = await fetch(`/api/search?q=${searchTerm}`);
setResults(await response.json());
},
[],
300, // 300ms delay
5000 // Max 5 seconds between searches
);
return (
);
}
```
--------------------------------
### useAsyncAbortable
Source: https://github.com/react-hookz/web/blob/master/README.md
Like `useAsync`, but also provides `AbortSignal` as first function argument to the async function.
```APIDOC
## useAsyncAbortable
### Description
Like `useAsync`, but also provides `AbortSignal` as first function argument to the async function.
### Usage
```javascript
const { execute, loading, data, error, abort } = useAsyncAbortable(asyncFunction, immediate);
```
### Parameters
- `asyncFunction` (function): The async function to execute. It receives an `AbortSignal` as its first argument.
- `immediate` (boolean, optional): If true, executes the function immediately on mount.
### Returns
- `execute` (function): Function to manually trigger the async function.
- `loading` (boolean): Indicates if the async function is currently executing.
- `data` (*): The result of the async function.
- `error` (Error): The error object if the async function failed.
- `abort` (function): Function to abort the ongoing async operation.
```
--------------------------------
### Track Most Recent Distinct Value with usePreviousDistinct
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Use usePreviousDistinct to get the most recent distinct value that is not equal to the current value using strict equality (===). It ignores consecutive identical values and returns undefined if all values have been the same.
```typescript
function ValueMonitor({ value }) {
const previousDistinct = usePreviousDistinct(value);
return (
Current: {value}
{previousDistinct !== undefined && (
Previous different: {previousDistinct}
)}
);
}
```
--------------------------------
### Track Previous Value with usePrevious
Source: https://github.com/react-hookz/web/blob/master/_autodocs/STATE_HOOKS.md
Use usePrevious to get the value passed to the hook on the previous render. It returns undefined on the first render and is updated in useEffect to avoid causing additional renders. Perfect for detecting value changes.
```typescript
function UserDetails({ userId }) {
const previousUserId = usePrevious(userId);
const [details, setDetails] = useState(null);
useEffect(() => {
if (userId !== previousUserId) {
fetch(`/api/users/${userId}`)
.then(r => r.json())
.then(setDetails);
}
}, [userId, previousUserId]);
return
{details?.name}
;
}
```
--------------------------------
### UseAsyncMeta
Source: https://github.com/react-hookz/web/blob/master/_autodocs/TYPES_REFERENCE.md
Metadata tracking for asynchronous operations, including the latest promise and arguments.
```APIDOC
## UseAsyncMeta
### Description
Metadata tracking for async operations.
### Type Definition
```typescript
type UseAsyncMeta = {
promise: Promise | undefined;
lastArgs: Args | undefined;
};
```
### Properties
- `promise` — Latest promise returned from execute
- `lastArgs` — Arguments from last execution call
```
--------------------------------
### useCookieValue Hook Example
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
Demonstrates how to use the useCookieValue hook to manage a language preference cookie. It includes options for expiration and sameSite attribute. The hook returns the current cookie value, a function to set the value, and a function to remove the cookie.
```typescript
function LanguagePicker() {
const [language, setLanguage, removeCookie] = useCookieValue('lang', {
expires: 365,
sameSite: 'Strict',
});
return (
);
}
```
--------------------------------
### useMountEffect
Source: https://github.com/react-hookz/web/blob/master/_autodocs/LIFECYCLE_HOOKS.md
Runs an effect only when the component mounts. This hook is equivalent to using `useEffect` with an empty dependency array.
```APIDOC
## useMountEffect
Runs an effect only when the component mounts (equivalent to useEffect with empty dependencies).
**Signature:**
```typescript
function useMountEffect(effect: CallableFunction): void
```
**Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| effect | `CallableFunction` | yes | Function to run on mount |
**Return Type:** `void`
**Behavior:**
- Effect runs once after first render
- Cleanup function is still supported (return from effect)
- Equivalent to `useEffect(effect, [])`
**Example:**
```typescript
function UserList() {
const [users, setUsers] = useState([]);
useMountEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers);
});
return (
{users.map(u =>
{u.name}
)}
);
}
```
```
--------------------------------
### UseWindowSizeOptions Type
Source: https://github.com/react-hookz/web/blob/master/_autodocs/TYPES_REFERENCE.md
Configuration options for the `useWindowSize` hook. Controls whether the hook initializes with a value.
```typescript
type UseWindowSizeOptions = {
initializeWithValue?: boolean;
};
```
--------------------------------
### Conditional Side Effect with useConditionalEffect
Source: https://github.com/react-hookz/web/blob/master/_autodocs/LIFECYCLE_HOOKS.md
Use `useConditionalEffect` to run a side effect, such as data fetching, only when specific conditions are met and dependencies change. This example fetches user data when the component is visible and a `userId` is available, using a custom predicate for condition evaluation.
```typescript
function DataFetcher({ userId, isVisible }) {
const [data, setData] = useState(null);
useConditionalEffect(
async () => {
const response = await fetch(`/api/users/${userId}`);
setData(await response.json());
},
[userId],
[isVisible, userId], // Conditions: component visible and userId provided
(conditions) => conditions[0] && conditions[1] !== undefined // Custom predicate
);
if (!isVisible) return null;
return
{data?.name}
;
}
```
--------------------------------
### useResizeObserver
Source: https://github.com/react-hookz/web/blob/master/_autodocs/SIDE_EFFECT_AND_SENSOR_HOOKS.md
Invokes a callback whenever ResizeObserver detects size changes on a target element. It optimizes performance by invoking the callback in an animation frame and pools observers for efficiency. Cleanup is handled automatically on unmount or target change.
```APIDOC
## useResizeObserver
### Description
Invokes a callback whenever ResizeObserver detects size changes on a target element.
### Signature
```typescript
function useResizeObserver(target: RefObject | T | null, callback: (entry: ResizeObserverEntry) => void, enabled?: boolean): void
```
### Parameters
#### Target
- **target** (`RefObject | T | null`) - Required - The element to observe.
#### Callback
- **callback** (`(entry) => void`) - Required - Called when size changes. Receives a `ResizeObserverEntry`.
#### Enabled
- **enabled** (`boolean`) - Optional - Enable or disable the observer. Defaults to `true`.
### Behavior
- Callback invoked in animation frame for performance.
- Pooled observers with the same target share a `ResizeObserver` instance.
- Automatic cleanup on unmount or target change.
### Example
```typescript
import { useRef, useState } from 'react';
import { useResizeObserver } from 'react-hookz';
function AspectRatioBox() {
const ref = useRef(null);
const [rect, setRect] = useState();
useResizeObserver(ref, (entry) => {
setRect(entry.contentRect);
});
return (
Content
);
}
```
```
--------------------------------
### UseAsyncActions
Source: https://github.com/react-hookz/web/blob/master/_autodocs/TYPES_REFERENCE.md
Actions available for the `useAsync` hook, including reset and execute functions.
```APIDOC
## UseAsyncActions
### Description
Actions available for useAsync.
### Type Definition
```typescript
type UseAsyncActions = {
reset: () => void;
execute: (...args: Args) => Promise;
};
```
### Generic Parameters
- `Result` — Type of async result
- `Args` — Types of arguments passed to async function
```
--------------------------------
### InitialState
Source: https://github.com/react-hookz/web/blob/master/_autodocs/TYPES_REFERENCE.md
Represents the initial state value or a function that returns the initial state.
```APIDOC
## InitialState
State initialization value or function.
```typescript
type InitialState = State | (() => State);
```
```
--------------------------------
### SSR-Safe Hook Initialization
Source: https://github.com/react-hookz/web/blob/master/_autodocs/README.md
Hooks like useMediaQuery, useWindowSize, and useScreenOrientation return undefined on the server. Use useEffect to prevent hydration mismatches by skipping rendering until these hooks are initialized on the client.
```typescript
// These return undefined on server, initialize on client:
const isMobile = useMediaQuery('(max-width: 768px)'); // undefined on server
const windowSize = useWindowSize(); // undefined on server
const orientation = useScreenOrientation(); // undefined on server
// Prevent hydration mismatch:
useEffect(() => {
if (isMobile === undefined) return; // Skip render if not initialized
// ...
}, [isMobile]);
```
--------------------------------
### CounterActions
Source: https://github.com/react-hookz/web/blob/master/_autodocs/TYPES_REFERENCE.md
Actions available for the `useCounter` hook, including increment, decrement, set, and reset.
```APIDOC
## CounterActions
### Description
Actions for useCounter.
### Type Definition
```typescript
type CounterActions = {
get: () => number;
inc: (delta?: SetStateAction) => void;
dec: (delta?: SetStateAction) => void;
set: (value: SetStateAction) => void;
reset: (value?: SetStateAction) => void;
};
```
```
--------------------------------
### SSR-Safe Window Size Initialization
Source: https://github.com/react-hookz/web/blob/master/_autodocs/DOM_AND_REF_HOOKS.md
Configure the hook with `{ initializeWithValue: false }` to prevent initial undefined values during Server-Side Rendering. The component will show a loading state until the window dimensions are available.
```typescript
// SSR-safe version
function SSRSafeComponent() {
const windowSize = useWindowSize({ initializeWithValue: false });
if (windowSize.width === undefined) {
return
Loading...
;
}
return
Size: {windowSize.width}x{windowSize.height}
;
}
```
--------------------------------
### useResizeObserver
Source: https://github.com/react-hookz/web/blob/master/README.md
Invokes a callback whenever `ResizeObserver` detects a change to the target's size.
```APIDOC
## useResizeObserver
### Description
Invokes a callback whenever `ResizeObserver` detects a change to the target's size.
### Usage
```javascript
useResizeObserver(ref, callback);
```
### Parameters
- `ref` (RefObject): A ref object to the target element.
- `callback` (function): The function to call when the element's size changes. It receives the `ResizeObserverEntry` as an argument.
```
--------------------------------
### useKeyboardEvent
Source: https://github.com/react-hookz/web/blob/master/README.md
Invokes a callback when a keyboard event occurs on the chosen target.
```APIDOC
## useKeyboardEvent
### Description
Invokes a callback when a keyboard event occurs on the chosen target.
### Usage
```javascript
useKeyboardEvent(target, eventName, handler, options);
```
### Parameters
- `target` (EventTarget): The target element to listen for keyboard events on.
- `eventName` (string): The name of the keyboard event (e.g., 'keydown', 'keyup').
- `handler` (function): The event handler function.
- `options` (object, optional): Options for the event listener.
```