### Install keyboardjs Peer Dependency
Source: https://github.com/streamich/react-use/blob/master/docs/useKeyboardJs.md
Shows the commands to install the `keyboardjs` library, which is a required peer dependency for the `useKeyboardJs` hook.
```bash
npm add keyboardjs
# or
yarn add keyboardjs
```
--------------------------------
### Install Rebound Peer Dependency
Source: https://github.com/streamich/react-use/blob/master/docs/useSpring.md
Install the 'rebound' library, which is a peer dependency for the useSpring hook.
```bash
npm add rebound
# or
yarn add rebound
```
--------------------------------
### Basic Usage of useStartTyping
Source: https://github.com/streamich/react-use/blob/master/docs/useStartTyping.md
Import and use the `useStartTyping` hook, providing a callback function to be executed when typing begins. This example shows a simple alert triggered by typing.
```jsx
import {useStartTyping} from 'react-use';
const Demo = () => {
useStartTyping(() => alert('Started typing...'));
return null;
};
```
--------------------------------
### Basic Usage of useKeyboardJs
Source: https://github.com/streamich/react-use/blob/master/docs/useKeyboardJs.md
Demonstrates how to use the `useKeyboardJs` hook to detect if a specific key combination ('a + b') is pressed. Ensure `keyboardjs` is installed as a peer dependency.
```jsx
import useKeyboardJs from 'react-use/lib/useKeyboardJs';
const Demo = () => {
const [isPressed] = useKeyboardJs('a + b');
return (
[a + b] pressed: {isPressed ? 'Yes' : 'No'}
);
};
```
--------------------------------
### useKey with String Filter
Source: https://github.com/streamich/react-use/blob/master/docs/useKey.md
This example shows how to use `useKey` with a simple string filter to detect when the 'a' key is pressed and trigger an alert. The handler function is provided as the second argument.
```javascript
useKey('a', () => alert('"a" pressed'));
```
--------------------------------
### Basic Usage of `useCookie`
Source: https://github.com/streamich/react-use/blob/master/docs/useCookie.md
Demonstrates how to use the `useCookie` hook to get, update, and delete a cookie. Includes setting an initial cookie value and updating it based on user interaction.
```jsx
import { useCookie } from "react-use";
import { useState, useEffect } from "react";
const Demo = () => {
const [value, updateCookie, deleteCookie] = useCookie("my-cookie");
const [counter, setCounter] = useState(1);
useEffect(() => {
deleteCookie();
}, []);
const updateCookieHandler = () => {
updateCookie(`my-awesome-cookie-${counter}`);
setCounter(c => c + 1);
};
return (
Value: {value}
);
};
```
--------------------------------
### Basic `useLocation` Usage
Source: https://github.com/streamich/react-use/blob/master/docs/useLocation.md
Demonstrates how to use the `useLocation` hook to get the current browser location. Ensure you have the necessary imports.
```jsx
import {useLocation} from 'react-use';
const Demo = () => {
const state = useLocation();
return (
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### Usage Example
Source: https://github.com/streamich/react-use/blob/master/docs/useUnmountPromise.md
Demonstrates how to use `useUnmountPromise` to wrap an asynchronous operation. The promise returned by `someFunction()` will not resolve if the component unmounts before it completes.
```typescript
import useUnmountPromise from 'react-use/lib/useUnmountPromise';
const Demo = () => {
const mounted = useUnmountPromise();
useEffect(async () => {
await mounted(someFunction()); // Will not resolve if component un-mounts.
});
};
```
--------------------------------
### useDrop Hook Example
Source: https://github.com/streamich/react-use/blob/master/docs/useDrop.md
Use the `useDrop` hook to track drop events across the entire page. It requires importing the hook and can handle files, URIs, and text.
```jsx
import {useDrop} from 'react-use';
const Demo = () => {
const state = useDrop({
onFiles: files => console.log('files', files),
onUri: uri => console.log('uri', uri),
onText: text => console.log('text', text),
});
return (
Drop something on the page.
);
};
```
--------------------------------
### Basic useGeolocation Usage
Source: https://github.com/streamich/react-use/blob/master/docs/useGeolocation.md
Demonstrates how to use the useGeolocation hook to get the current location state and display it. Accepts PositionOptions.
```jsx
import {useGeolocation} from 'react-use';
const Demo = () => {
const state = useGeolocation();
return (
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### Basic useCss Usage
Source: https://github.com/streamich/react-use/blob/master/docs/useCss.md
Import and use the useCss hook to apply styles and pseudo-selectors to an element. This example demonstrates changing text color on hover.
```jsx
import {useCss} from 'react-use';
const Demo = () => {
const className = useCss({
color: 'red',
border: '1px solid red',
'&:hover': {
color: 'blue',
},
});
return (
Hover me!
);
};
```
--------------------------------
### Basic Usage of useUpdate
Source: https://github.com/streamich/react-use/blob/master/docs/useUpdate.md
Import `useUpdate` and call the returned function to force a re-render. This example shows updating a timestamp when the button is clicked.
```jsx
import {useUpdate} from 'react-use';
const Demo = () => {
const update = useUpdate();
return (
<>
Time: {Date.now()}
>
);
};
```
--------------------------------
### Basic Usage of useWindowSize
Source: https://github.com/streamich/react-use/blob/master/docs/useWindowSize.md
Import and use the hook to get the current window width and height. This is useful for displaying dimensions or conditionally rendering components.
```jsx
import {useWindowSize} from 'react-use';
const Demo = () => {
const {width, height} = useWindowSize();
return (
width: {width}
height: {height}
);
};
```
--------------------------------
### useStateList Usage Example
Source: https://github.com/streamich/react-use/blob/master/docs/useStateList.md
Demonstrates how to use the useStateList hook to manage and iterate through a list of states. Includes controls for previous, next, setting state by index, and setting state by value.
```jsx
import { useStateList } from 'react-use';
import { useRef } from 'react';
const stateSet = ['first', 'second', 'third', 'fourth', 'fifth'];
const Demo = () => {
const { state, prev, next, setStateAt, setState, currentIndex, isFirst, isLast } = useStateList(stateSet);
const indexInput = useRef(null);
const stateInput = useRef(null);
return (
);
};
```
--------------------------------
### Logging Component Lifecycle with `useLogger`
Source: https://github.com/streamich/react-use/blob/master/docs/useLogger.md
Use this snippet to log component name and props as it mounts, updates, and unmounts. Ensure `react-use` is installed and imported.
```jsx
import {useLogger} from 'react-use';
const Demo = (props) => {
useLogger('Demo', props);
return null;
};
```
--------------------------------
### Basic useDebounce Example
Source: https://github.com/streamich/react-use/blob/master/docs/useDebounce.md
Demonstrates how to use the useDebounce hook to update a debounced value after the user stops typing for a specified duration. It also shows how to cancel the debounce operation.
```jsx
const Demo = () => {
const [state, setState] = React.useState('Typing stopped');
const [val, setVal] = React.useState('');
const [debouncedValue, setDebouncedValue] = React.useState('');
const [, cancel] = useDebounce(
() => {
setState('Typing stopped');
setDebouncedValue(val);
},
2000,
[val]
);
return (
{
setState('Waiting for typing to stop...');
setVal(currentTarget.value);
}}
/>
{state}
Debounced value: {debouncedValue}
);
};
```
--------------------------------
### Basic Usage of useHash Hook
Source: https://github.com/streamich/react-use/blob/master/docs/useHash.md
Demonstrates how to use the `useHash` hook to get the current URL hash and update it. The hook automatically synchronizes with the browser's `hashchange` event.
```jsx
import {useHash} from 'react-use';
const Demo = () => {
const [hash, setHash] = useHash();
useMount(() => {
setHash('#/path/to/page?userId=123');
});
return (
window.location.href:
{window.location.href}
Edit hash:
setHash(e.target.value)} />
);
};
```
--------------------------------
### useCss with Media Queries
Source: https://github.com/streamich/react-use/blob/master/docs/useCss.md
Implement responsive styles using media queries within the useCss hook. This example changes text color on hover based on screen width.
```javascript
const className = useCss({
color: 'tomato',
'@media only screen and (max-width: 600px)': {
color: 'orange',
'&:hover': {
color: 'red',
}
},
});
```
--------------------------------
### Basic useMotion Hook Usage
Source: https://github.com/streamich/react-use/blob/master/docs/useMotion.md
Demonstrates how to use the `useMotion` hook to get motion sensor data. Import the hook and use it to retrieve the current motion state, which can then be displayed or processed.
```jsx
import {useMotion} from 'react-use';
const Demo = () => {
const state = useMotion();
return (
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### Basic Usage of useRafLoop
Source: https://github.com/streamich/react-use/blob/master/docs/useRafLoop.md
Demonstrates how to use useRafLoop to trigger a callback function on each animation frame. The hook provides start, stop, and isActive functions to control the loop.
```jsx
import * as React from 'react';
import { useRafLoop, useUpdate } from 'react-use';
const Demo = () => {
const [ticks, setTicks] = React.useState(0);
const [lastCall, setLastCall] = React.useState(0);
const update = useUpdate();
const [loopStop, loopStart, isActive] = useRafLoop((time) => {
setTicks(ticks => ticks + 1);
setLastCall(time);
});
return (
RAF triggered: {ticks} (times)
Last high res timestamp: {lastCall}
);
};
```
--------------------------------
### Basic Usage of useNetworkState
Source: https://github.com/streamich/react-use/blob/master/docs/useNetworkState.md
Demonstrates how to use the useNetworkState hook to get the current network state and display it as a JSON string. This is useful for monitoring network connectivity in a React application.
```jsx
import {useNetworkState} from 'react-use';
const Demo = () => {
const state = useNetworkState();
return (
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### useSetState Reference Examples
Source: https://github.com/streamich/react-use/blob/master/docs/useSetState.md
Illustrates direct state updates and functional state updates using the setState function returned by useSetState. Useful for incrementing counters or applying changes based on the previous state.
```js
const [state, setState] = useSetState({cnt: 0});
setState({cnt: state.cnt + 1});
setState((prevState) => ({
cnt: prevState + 1,
}));
```
--------------------------------
### Basic Usage of useIdle Hook
Source: https://github.com/streamich/react-use/blob/master/docs/useIdle.md
Demonstrates how to use the `useIdle` hook to track user idleness. The hook takes a time in milliseconds (3000ms in this example) after which the user is considered idle. It returns a boolean value.
```jsx
import {useIdle} from 'react-use';
const Demo = () => {
const isIdle = useIdle(3e3);
return (
User is idle: {isIdle ? 'Yes 😴' : 'Nope'}
);
};
```
--------------------------------
### Shared Text Input Example
Source: https://github.com/streamich/react-use/blob/master/docs/createStateContext.md
Demonstrates sharing text state between two input fields using createStateContext. Ensure the provider wraps the components that need access to the shared state.
```jsx
import { createStateContext } from 'react-use';
const [useSharedText, SharedTextProvider] = createStateContext('');
const ComponentA = () => {
const [text, setText] = useSharedText();
return (
);
};
```
--------------------------------
### Create and Use a Shared Counter Context
Source: https://github.com/streamich/react-use/blob/master/docs/createReducerContext.md
This example demonstrates how to create a shared counter context using `createReducerContext`. It defines a reducer function, an initial state, and then uses the generated hook and provider to manage and display a shared counter value across two components.
```jsx
import { createReducerContext } from 'react-use';
type Action = 'increment' | 'decrement';
const reducer = (state: number, action: Action) => {
switch (action) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
throw new Error();
}
};
const [useSharedCounter, SharedCounterProvider] = createReducerContext(reducer, 0);
const ComponentA = () => {
const [count, dispatch] = useSharedCounter();
return (
);
};
```
--------------------------------
### Basic Usage of usePageLeave
Source: https://github.com/streamich/react-use/blob/master/docs/usePageLeave.md
This snippet demonstrates the basic implementation of the `usePageLeave` hook. It takes a callback function that will be executed when the mouse leaves the page. No additional setup is required beyond importing the hook.
```jsx
import {usePageLeave} from 'react-use';
const Demo = () => {
usePageLeave(() => console.log('Page left...'));
return null;
};
```
--------------------------------
### Reference for createReducerContext
Source: https://github.com/streamich/react-use/blob/master/docs/createReducerContext.md
This reference shows the basic structure for using `createReducerContext`. It highlights how to create the context hook and provider, and how to optionally override the initial state when using the provider.
```jsx
const [useSharedState, SharedStateProvider] = createReducerContext(reducer, initialState);
// In wrapper
const Wrapper = ({ children }) => (
// You can override the initial state for each Provider
{ children }
)
// In a component
const Component = () => {
const [sharedState, dispatch] = useSharedState();
// ...
}
```
--------------------------------
### useFirstMountState Reference
Source: https://github.com/streamich/react-use/blob/master/docs/useFirstMountState.md
Shows the basic signature for using the `useFirstMountState` hook.
```typescript
const isFirstMount: boolean = useFirstMountState();
```
--------------------------------
### Get Screen Orientation State
Source: https://github.com/streamich/react-use/blob/master/docs/useOrientation.md
Import and use the `useOrientation` hook to get the current device orientation. The hook returns an object with `angle` and `type` properties.
```jsx
import {useOrientation} from 'react-use';
const Demo = () => {
const state = useOrientation();
return (
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### useRendersCount Reference
Source: https://github.com/streamich/react-use/blob/master/docs/useRendersCount.md
Shows the basic signature for using the useRendersCount hook to get the current render count.
```typescript
const rendersCount: number = useRendersCount();
```
--------------------------------
### Basic Usage of useAsync
Source: https://github.com/streamich/react-use/blob/master/docs/useAsync.md
Demonstrates how to use the useAsync hook to fetch data from a URL and display its loading, error, or value state.
```jsx
import {useAsync} from 'react-use';
const Demo = ({url}) => {
const state = useAsync(async () => {
const response = await fetch(url);
const result = await response.text();
return result
}, [url]);
return (
{state.loading
?
Loading...
: state.error
?
Error: {state.error.message}
:
Value: {state.value}
}
);
};
```
--------------------------------
### Basic Usage of useCounter
Source: https://github.com/streamich/react-use/blob/master/docs/useCounter.md
Demonstrates how to initialize and use the useCounter hook with optional min/max bounds and various control functions.
```jsx
import {useCounter, useNumber} from 'react-use';
const Demo = () => {
const [min, { inc: incMin, dec: decMin }] = useCounter(1);
const [max, { inc: incMax, dec: decMax }] = useCounter(10);
const [value, { inc, dec, set, reset }] = useCounter(5, max, min);
return (
current: { value } [min: { min }; max: { max }]
Current value:
Min value:
Max value:
);
};
```
--------------------------------
### Basic Usage of useFirstMountState
Source: https://github.com/streamich/react-use/blob/master/docs/useFirstMountState.md
Demonstrates how to use `useFirstMountState` to check if a component is on its first mount. It re-renders the component on button click to show the state change.
```typescript jsx
import * as React from 'react';
import { useFirstMountState } from 'react-use';
const Demo = () => {
const isFirstMount = useFirstMountState();
const update = useUpdate();
return (
This component is just mounted: {isFirstMount ? 'YES' : 'NO'}
);
};
```
--------------------------------
### useCss with Pseudo-selectors
Source: https://github.com/streamich/react-use/blob/master/docs/useCss.md
Apply styles to an element and its pseudo-selectors using the useCss hook. This example shows changing color on hover.
```javascript
const className = useCss({
color: 'tomato',
'&:hover': {
color: 'orange',
},
});
```
--------------------------------
### useKey with Predicate Function and Options
Source: https://github.com/streamich/react-use/blob/master/docs/useKey.md
This snippet demonstrates using `useKey` with a predicate function for more complex key filtering. It also shows how to specify event options, such as listening for the 'keyup' event instead of the default 'keydown'.
```javascript
const predicate = (event) => event.key === 'a'
useKey(predicate, handler, {event: 'keyup'});
```
--------------------------------
### useMount
Source: https://github.com/streamich/react-use/blob/master/docs/useMount.md
Calls a function after the component is mounted. This is useful for performing side effects or setup operations that should only occur once when the component initially renders.
```APIDOC
## useMount
### Description
Executes a callback function exactly once after the component has mounted.
### Usage
```jsx
import { useMount } from 'react-use';
const MyComponent = () => {
useMount(() => {
// Code to run after component mounts
console.log('Component has mounted!');
});
return
My Component
;
};
```
### Reference
```ts
useMount(callback: () => void)
```
#### Parameters
* **callback** (function) - Required - The function to execute after the component mounts.
```
--------------------------------
### Basic useTween Usage
Source: https://github.com/streamich/react-use/blob/master/docs/useTween.md
Demonstrates the basic implementation of the useTween hook to animate a value. Import the hook and use it to get the animated number.
```jsx
import {useTween} from 'react-use';
const Demo = () => {
const t = useTween();
return (
Tween: {t}
);
};
```
--------------------------------
### Basic Usage of useQueue
Source: https://github.com/streamich/react-use/blob/master/docs/useQueue.md
Demonstrates how to use the useQueue hook to manage a FIFO queue. Includes adding, removing, and displaying queue properties like first, last, and size.
```jsx
import { useQueue } from 'react-use';
const Demo = () => {
const { add, remove, first, last, size } = useQueue();
return (
first: {first}
last: {last}
size: {size}
);
};
```
--------------------------------
### useAudio Hook Reference
Source: https://github.com/streamich/react-use/blob/master/docs/useAudio.md
Illustrates the different ways to initialize the useAudio hook, either by passing props directly or by providing a pre-defined audio element.
```jsx
const [audio, state, controls, ref] = useAudio(props);
```
```jsx
const [audio, state, controls] = useAudio();
```
--------------------------------
### Basic Usage of useAudio Hook
Source: https://github.com/streamich/react-use/blob/master/docs/useAudio.md
Demonstrates how to use the useAudio hook to manage an audio player, including displaying the audio element, its state, and playback controls. Ensure the audio source URL is valid.
```jsx
import {useAudio} from 'react-use';
const Demo = () => {
const [audio, state, controls, ref] = useAudio({
src: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
autoPlay: true,
});
return (
{audio}
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### Basic Pinch Zoom Implementation
Source: https://github.com/streamich/react-use/blob/master/docs/usePinchZoom.md
This snippet demonstrates how to use the `usePinchZoom` hook to detect zoom in and zoom out gestures on an image. It requires importing the hook and setting up a ref for the target element.
```jsx
import { usePinchZoom } from "react-use";
const Demo = () => {
const [scale, setState] = useState(1);
const scaleRef = useRef();
const { zoomingState, pinchState } = usePinchZoom(scaleRef);
useEffect(() => {
if (zoomingState === "ZOOM_IN") {
// perform zoom in scaling
setState(scale + 0.1)
} else if (zoomingState === "ZOOM_OUT") {
// perform zoom out in scaling
setState(scale - 0.1)
}
}, [zoomingState]);
return (
);
};
```
--------------------------------
### usePreviousDistinct with Custom Comparator
Source: https://github.com/streamich/react-use/blob/master/docs/usePreviousDistinct.md
Shows how to use `usePreviousDistinct` with a custom comparison function to determine value distinctness, ignoring case in this example. Import `usePreviousDistinct` from 'react-use'.
```jsx
import {usePreviousDistinct} from 'react-use';
const Demo = () => {
const [str, setStr] = React.useState("something_lowercase");
const [unrelatedCount] = React.useState(0);
const prevStr = usePreviousDistinct(str, (prev, next) => (prev && prev.toUpperCase()) === next.toUpperCase());
return (
);
};
```
--------------------------------
### useEvent with Different Event Types and Options
Source: https://github.com/streamich/react-use/blob/master/docs/useEvent.md
Illustrates using useEvent with different event types like 'keydown' and 'scroll'. It also shows how to specify a target element (window) and event options like {capture: true}.
```js
useEvent('keydown', handler)
useEvent('scroll', handler, window, {capture: true})
```
--------------------------------
### Basic Usage of useInterval Hook
Source: https://github.com/streamich/react-use/blob/master/docs/useInterval.md
Demonstrates how to use the useInterval hook to increment a counter at a specified delay. The interval can be started or stopped by toggling a boolean state.
```jsx
import * as React from 'react';
import {useInterval} from 'react-use';
const Demo = () => {
const [count, setCount] = React.useState(0);
const [delay, setDelay] = React.useState(1000);
const [isRunning, toggleIsRunning] = useBoolean(true);
useInterval(
() => {
setCount(count + 1);
},
isRunning ? delay : null
);
return (
delay: setDelay(Number(event.target.value))} />
count: {count}
);
};
```
--------------------------------
### Basic Usage of useScroll
Source: https://github.com/streamich/react-use/blob/master/docs/useScroll.md
Import and use the useScroll hook to get scroll coordinates (x, y) from a referenced DOM element. The component will re-render as the scroll position changes.
```jsx
import {useScroll} from 'react-use';
const Demo = () => {
const scrollRef = React.useRef(null);
const {x, y} = useScroll(scrollRef);
return (
x: {x}
y: {y}
);
};
```
--------------------------------
### Basic Usage of useToggle
Source: https://github.com/streamich/react-use/blob/master/docs/useToggle.md
Demonstrates how to use the useToggle hook to manage a boolean state and toggle it. Includes setting the initial state and explicitly setting the state to true or false.
```jsx
import {useToggle} from 'react-use';
const Demo = () => {
const [on, toggle] = useToggle(true);
return (
{on ? 'ON' : 'OFF'}
);
};
```
--------------------------------
### Track Media Devices with useMediaDevices
Source: https://github.com/streamich/react-use/blob/master/docs/useMediaDevices.md
Import and use the `useMediaDevices` hook to get the current state of connected media devices. The state object can be directly stringified for display.
```jsx
import {useMediaDevices} from 'react-use';
const Demo = () => {
const state = useMediaDevices();
return (
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### Reference for createMemo
Source: https://github.com/streamich/react-use/blob/master/docs/createMemo.md
Shows the basic signature for using `createMemo`. It takes a function `fn` as an argument and returns a memoized hook `useMemoFn`.
```js
const useMemoFn = createMemo(fn);
```
--------------------------------
### Basic Usage of useMeasure
Source: https://github.com/streamich/react-use/blob/master/docs/useMeasure.md
Demonstrates how to use the useMeasure hook to get the dimensions of a div element. The hook returns a ref to attach to the element and an object containing its dimensions.
```jsx
import { useMeasure } from "react-use";
const Demo = () => {
const [ref, { x, y, width, height, top, right, bottom, left }] = useMeasure();
return (
x: {x}
y: {y}
width: {width}
height: {height}
top: {top}
right: {right}
bottom: {bottom}
left: {left}
);
};
```
--------------------------------
### Basic Usage of useList
Source: https://github.com/streamich/react-use/blob/master/docs/useList.md
Demonstrates how to use the `useList` hook to manage an array and its modifications. Use the provided actions (set, push, updateAt, etc.) to update the list and trigger re-renders.
```jsx
import {useList} from 'react-use';
const Demo = () => {
const [list, { set, push, updateAt, insertAt, update, updateFirst, upsert, sort, filter, removeAt, clear, reset }] = useList([1, 2, 3, 4, 5]);
return (
{JSON.stringify(list, null, 2)}
);
};
```
--------------------------------
### Basic Usage of useMount
Source: https://github.com/streamich/react-use/blob/master/docs/useMount.md
This snippet demonstrates the basic usage of the useMount hook. It calls an alert function immediately after the component mounts. Ensure you import useMount from 'react-use'.
```jsx
import {useMount} from 'react-use';
const Demo = () => {
useMount(() => alert('MOUNTED'));
return null;
};
```
--------------------------------
### Basic Usage of useAsyncFn
Source: https://github.com/streamich/react-use/blob/master/docs/useAsyncFn.md
Demonstrates how to use useAsyncFn to fetch data from a URL and display its loading, error, or value state. The async function is defined inline and depends on the 'url' prop.
```jsx
import {useAsyncFn} from 'react-use';
const Demo = ({url}) => {
const [state, doFetch] = useAsyncFn(async () => {
const response = await fetch(url);
const result = await response.text();
return result
}, [url]);
return (
{state.loading
?
Loading...
: state.error
?
Error: {state.error.message}
:
Value: {state.value}
}
);
};
```
--------------------------------
### Basic Usage of useThrottle
Source: https://github.com/streamich/react-use/blob/master/docs/useThrottle.md
Demonstrates how to use the `useThrottle` hook to limit the rate at which a value is updated. Import the hook and pass the value and optional delay in milliseconds.
```jsx
import React, { useState } from 'react';
import { useThrottle, useThrottleFn } from 'react-use';
const Demo = ({value}) => {
const throttledValue = useThrottle(value);
// const throttledValue = useThrottleFn(value => value, 200, [value]);
return (
<>
Value: {value}
Throttled value: {throttledValue}
>
);
};
```
--------------------------------
### useUpdateEffect Basic Usage
Source: https://github.com/streamich/react-use/blob/master/docs/useUpdateEffect.md
Demonstrates how `useUpdateEffect` ignores the first render. The effect logs the count starting from the second render onwards. An optional cleanup function can be returned.
```jsx
import React from 'react'
import {useUpdateEffect} from 'react-use';
const Demo = () => {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(() => {
setCount(count => count + 1)
}, 1000)
return () => {
clearInterval(interval)
}
}, [])
useUpdateEffect(() => {
console.log('count', count) // will only show 1 and beyond
return () => { // *OPTIONAL*
// do something on unmount
}
}) // you can include deps array if necessary
return
Count: {count}
};
```
--------------------------------
### Basic Usage of useSet Hook
Source: https://github.com/streamich/react-use/blob/master/docs/useSet.md
Demonstrates how to initialize and use the `useSet` hook with its associated methods for managing a Set of strings. The 'reset' method restores the Set to its initial state, while 'clear' empties it.
```jsx
import {useSet} from 'react-use';
const Demo = () => {
const [set, { add, has, remove, toggle, reset, clear }] = useSet(new Set(['hello']));
return (
{JSON.stringify(Array.from(set), null, 2)}
);
};
```
--------------------------------
### `useMethods` Reference
Source: https://github.com/streamich/react-use/blob/master/docs/useMethods.md
Shows the signature for calling `useMethods`. It accepts a `createMethods` function and an `initialState`.
```js
const [state, methods] = useMethods(createMethods, initialState);
```
--------------------------------
### useHover and useHoverDirty Reference
Source: https://github.com/streamich/react-use/blob/master/docs/useHover.md
Illustrates the different ways to call `useHover` and `useHoverDirty` based on the documentation reference. `useHover` can accept a React element directly or a function returning one, while `useHoverDirty` takes a React ref.
```js
const [newReactElement, isHovering] = useHover(reactElement);
const [newReactElement, isHovering] = useHover((isHovering) => reactElement);
const isHovering = useHoverDirty(ref);
```
--------------------------------
### Basic `useMethods` Usage
Source: https://github.com/streamich/react-use/blob/master/docs/useMethods.md
Demonstrates how to use `useMethods` to manage a simple counter state with increment, decrement, and reset functionalities. Ensure `useMethods` is imported from 'react-use'.
```jsx
import { useMethods } from 'react-use';
const initialState = {
count: 0,
};
function createMethods(state) {
return {
reset() {
return initialState;
},
increment() {
return { ...state, count: state.count + 1 };
},
decrement() {
return { ...state, count: state.count - 1 };
},
};
}
const Demo = () => {
const [state, methods] = useMethods(createMethods, initialState);
return (
<>
Count: {state.count}
>
);
};
```
--------------------------------
### Use Default Breakpoints
Source: https://github.com/streamich/react-use/blob/master/docs/createBreakpoint.md
This snippet demonstrates how to use the `createBreakpoint` hook with its default breakpoint values (laptopL: 1440, laptop: 1024, tablet: 768). It shows how to conditionally render content based on the current screen size.
```jsx
import React from "react";
import { createBreakpoint } from "react-use";
const useBreakpoint = createBreakpoint();
const Demo = () => {
const breakpoint = useBreakpoint();
if (breakpoint === "laptopL") return
This is very big Laptop
;
else if (breakpoint == "laptop") return
This is Laptop
;
else if (breakpoint == "tablet") return
This is Tablet
;
else return
Too small!
;
};
```
--------------------------------
### Babel Plugin Import Configuration
Source: https://github.com/streamich/react-use/blob/master/docs/Usage.md
Configure babel-plugin-import to transform named imports into individual imports for better tree shaking. This setup helps resolve potential dependency errors.
```json
[
'import',
{
libraryName: 'react-use',
camel2DashComponentName: false,
customName(/** @type {string} */ name) {
const libraryDirectory = name.startsWith('Use')
? 'lib/component'
: name.startsWith('create')
? 'lib/factory'
: 'lib'
return `react-use/${libraryDirectory}/${name}`
}
},
'import-react-use'
]
```
--------------------------------
### Basic Video Playback Control
Source: https://github.com/streamich/react-use/blob/master/docs/useVideo.md
Demonstrates how to use the useVideo hook to embed a video, display its state, and control playback with buttons. Requires importing the hook and using it with a video element.
```jsx
import {useVideo} from 'react-use';
const Demo = () => {
const [video, state, controls, ref] = useVideo(
);
return (
{video}
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### Get Scrollbar Width in React Component
Source: https://github.com/streamich/react-use/blob/master/docs/useScrollbarWidth.md
Use this snippet to display the browser's scrollbar width within a React component. It handles the initial undefined state before DOM readiness.
```jsx
const Demo = () => {
const sbw = useScrollbarWidth();
return (
{sbw === undefined ? `DOM is not ready yet, SBW detection delayed` : `Browser's scrollbar width is ${sbw}px`}
);
};
```
--------------------------------
### Basic Usage of useRafState
Source: https://github.com/streamich/react-use/blob/master/docs/useRafState.md
Demonstrates how to use useRafState to manage component state that needs to be updated efficiently, such as during window resize events. It ensures state updates are batched and synchronized with the animation frame.
```jsx
import {useRafState, useMount} from 'react-use';
const Demo = () => {
const [state, setState] = useRafState({
width: 0,
height: 0,
});
useMount(() => {
const onResize = () => {
setState({
width: window.clientWidth,
height: window.height,
});
};
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
});
return
{JSON.stringify(state, null, 2)}
;
};
```
--------------------------------
### Query Microphone Permission Status
Source: https://github.com/streamich/react-use/blob/master/docs/usePermission.md
This snippet demonstrates how to use the usePermission hook to get the current permission state for the microphone. It returns an object containing the permission state, which can be displayed in the UI.
```jsx
import {usePermission} from 'react-use';
const Demo = () => {
const state = usePermission({ name: 'microphone' });
return (
{JSON.stringify(state, null, 2)}
);
};
```
--------------------------------
### Basic Usage of useKeyPress
Source: https://github.com/streamich/react-use/blob/master/docs/useKeyPress.md
Demonstrates how to use the useKeyPress hook to track multiple number keys. It returns an array where the first element indicates if the key is pressed.
```jsx
import {useKeyPress} from 'react-use';
const keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
const Demo = () => {
const states = [];
for (const key of keys) states.push(useKeyPress(key)[0]);
return (
);
};
```
--------------------------------
### Basic Usage of useCopyToClipboard
Source: https://github.com/streamich/react-use/blob/master/docs/useCopyToClipboard.md
Demonstrates how to use the useCopyToClipboard hook to copy text from an input field to the clipboard. It shows how to handle the copied value and potential errors.
```jsx
const Demo = () => {
const [text, setText] = React.useState('');
const [state, copyToClipboard] = useCopyToClipboard();
return (
setText(e.target.value)} />
{state.error
?
Unable to copy value: {state.error.message}
: state.value &&
Copied {state.value}
}
)
}
```
--------------------------------
### Basic Usage of useLocalStorage
Source: https://github.com/streamich/react-use/blob/master/docs/useLocalStorage.md
Demonstrates how to use the useLocalStorage hook to manage a string value in localStorage. Includes setting initial value, updating the value, and removing it.
```jsx
import { useLocalStorage } from 'react-use';
const Demo = () => {
const [value, setValue, remove] = useLocalStorage('my-key', 'foo');
return (
Value: {value}
);
};
```
--------------------------------
### Using ensuredForwardRef Directly
Source: https://github.com/streamich/react-use/blob/master/docs/useEnsuredForwardedRef.md
This example demonstrates how to use `ensuredForwardRef` as a higher-order component to wrap a functional component, ensuring the forwarded ref is always valid within the component's lifecycle.
```jsx
import {ensuredForwardRef} from 'react-use';
const Demo = () => {
return (
);
};
const Child = ensuredForwardRef((props, ref) => {
useEffect(() => {
console.log(ref.current.getBoundingClientRect())
}, [])
return (
);
});
```