What is react-use?
The react-use library is a collection of essential React hooks that simplify the development process by providing pre-built solutions for common tasks. Whether you’re managing state, handling side effects, or dealing with UI elements, react-use offers a wide range of hooks that can enhance your React applications.
Installation
To get started with react-use, you can install it using either npm or yarn:
# Using npm
npm install react-use
# Using yarn
yarn add react-use
Basic Usage with Code Examples
Let’s explore some basic hooks provided by react-use.
useToggle
The useToggle
hook is a simple way to manage boolean state. It provides a boolean value and a function to toggle it.
import React from 'react';
import { useToggle } from 'react-use';
const ToggleComponent: React.FC = () => {
const [isToggled, toggle] = useToggle(false);
return (
<div>
<button onClick={toggle}>
{isToggled ? 'ON' : 'OFF'}
</button>
</div>
);
};
export default ToggleComponent;
useLocalStorage
The useLocalStorage
hook allows you to persist state in the browser’s local storage.
import React from 'react';
import { useLocalStorage } from 'react-use';
const LocalStorageComponent: React.FC = () => {
const [value, setValue] = useLocalStorage<string>('my-key', 'initial');
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} />
</div>
);
};
export default LocalStorageComponent;
Advanced Usage with Code Examples
For more complex scenarios, react-use offers advanced hooks.
useAsync
The useAsync
hook is useful for handling asynchronous operations. It provides state and actions for managing async processes.
import React from 'react';
import { useAsync } from 'react-use';
const fetchData = async (): Promise<string> => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data.message;
};
const AsyncComponent: React.FC = () => {
const { loading, error, value } = useAsync(fetchData);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Data: {value}</div>;
};
export default AsyncComponent;
useAsyncFn
The useAsyncFn
hook is similar to useAsync
but provides more control by allowing you to trigger the asynchronous function manually.
import React from 'react';
import { useAsyncFn } from 'react-use';
const fetchData = async (): Promise<string> => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data.message;
};
const AsyncFnComponent: React.FC = () => {
const [state, fetch] = useAsyncFn(fetchData, []);
return (
<div>
<button onClick={() => fetch()}>Fetch Data</button>
{state.loading && <div>Loading...</div>}
{state.error && <div>Error: {state.error.message}</div>}
{state.value && <div>Data: {state.value}</div>}
</div>
);
};
export default AsyncFnComponent;
useAsyncRetry
The useAsyncRetry
hook is designed for retrying asynchronous operations until they succeed or a certain condition is met.
import React from 'react';
import { useAsyncRetry } from 'react-use';
const fetchData = async (): Promise<string> => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data.message;
};
const AsyncRetryComponent: React.FC = () => {
const state = useAsyncRetry(fetchData);
return (
<div>
<button onClick={() => state.retry()}>Retry</button>
{state.loading && <div>Loading...</div>}
{state.error && <div>Error: {state.error.message}</div>}
{state.value && <div>Data: {state.value}</div>}
</div>
);
};
export default AsyncRetryComponent;
useAudio
The useAudio
hook provides a simple way to manage audio playback in your React application.
import React from 'react';
import { useAudio } from 'react-use';
const AudioComponent: React.FC = () => {
const [audio, state, controls] = useAudio({
src: 'https://www.example.com/audio.mp3',
autoPlay: false,
});
return (
<div>
{audio}
<button onClick={controls.play}>Play</button>
<button onClick={controls.pause}>Pause</button>
<button onClick={controls.mute}>Mute</button>
</div>
);
};
export default AudioComponent;
useBattery
The useBattery
hook provides information about the device’s battery status, such as charging status and battery level.
import React from 'react';
import { useBattery } from 'react-use';
const BatteryComponent: React.FC = () => {
const batteryState = useBattery();
return (
<div>
<p>Battery Level: {batteryState.level * 100}%</p>
<p>Charging: {batteryState.charging ? 'Yes' : 'No'}</p>
</div>
);
};
export default BatteryComponent;
useBeforeUnload
The useBeforeUnload
hook allows you to prompt the user with a confirmation dialog when they attempt to leave the page.
import React from 'react';
import { useBeforeUnload } from 'react-use';
const BeforeUnloadComponent: React.FC = () => {
useBeforeUnload(() => 'Are you sure you want to leave?');
return <div>Try to leave this page!</div>;
};
export default BeforeUnloadComponent;
useClickAway
The useClickAway
hook detects clicks outside of a specified element, which is useful for closing dropdowns or modals.
import React, { useRef } from 'react';
import { useClickAway } from 'react-use';
const ClickAwayComponent: React.FC = () => {
const ref = useRef(null);
useClickAway(ref, () => {
alert('Clicked outside!');
});
return <div ref={ref}>Click outside this box</div>;
};
export default ClickAwayComponent;
useCookie
The useCookie
hook provides a way to manage cookies in your application.
import React from 'react';
import { useCookie } from 'react-use';
const CookieComponent: React.FC = () => {
const [value, updateCookie, deleteCookie] = useCookie('my-cookie');
return (
<div>
<p>Cookie Value: {value}</p>
<button onClick={() => updateCookie('new-value')}>Update Cookie</button>
<button onClick={deleteCookie}>Delete Cookie</button>
</div>
);
};
export default CookieComponent;
useCopyToClipboard
The useCopyToClipboard
hook provides a mechanism to copy text to the clipboard.
import React from 'react';
import { useCopyToClipboard } from 'react-use';
const CopyToClipboardComponent: React.FC = () => {
const [state, copyToClipboard] = useCopyToClipboard();
return (
<div>
<button onClick={() => copyToClipboard('Hello, world!')}>
Copy to Clipboard
</button>
{state.error && <p>Error: {state.error.message}</p>}
{state.value && <p>Copied: {state.value}</p>}
</div>
);
};
export default CopyToClipboardComponent;
useCounter
The useCounter
hook provides a simple counter with increment and decrement functions.
import React from 'react';
import { useCounter } from 'react-use';
const CounterComponent: React.FC = () => {
const [count, { inc, dec, reset }] = useCounter(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => inc()}>Increment</button>
<button onClick={() => dec()}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
};
export default CounterComponent;
useCss
The useCss
hook allows you to dynamically create and manage CSS styles.
import React from 'react';
import { useCss } from 'react-use';
const CssComponent: React.FC = () => {
const className = useCss({
color: 'red',
fontSize: '20px',
});
return <div className={className}>Styled Text</div>;
};
export default CssComponent;
useCustomCompareEffect
The useCustomCompareEffect
hook is similar to useEffect
, but it allows you to customize the comparison logic for dependencies.
import React, { useState } from 'react';
import { useCustomCompareEffect } from 'react-use';
import isEqual from 'lodash/isEqual';
const CustomCompareEffectComponent: React.FC = () => {
const [data, setData] = useState({ key: 'value' });
useCustomCompareEffect(() => {
console.log('Effect triggered');
}, [data], isEqual);
return <div>Check the console</div>;
};
export default CustomCompareEffectComponent;
useDebounce
The useDebounce
hook helps to delay the execution of a function, which is useful for optimizing performance in response to rapid changes.
import React, { useState } from 'react';
import { useDebounce } from 'react-use';
const DebounceComponent: React.FC = () => {
const [text, setText] = useState('');
const debouncedText = useDebounce(text, 500);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<p>Debounced Value: {debouncedText}</p>
</div>
);
};
export default DebounceComponent;
useDeepCompareEffect
The useDeepCompareEffect
hook is a variant of useEffect
that performs a deep comparison of dependencies, ensuring the effect only runs when the dependencies truly change.
import React, { useState } from 'react';
import { useDeepCompareEffect } from 'react-use';
const DeepCompareEffectComponent: React.FC = () => {
const [data, setData] = useState({ key: 'value' });
useDeepCompareEffect(() => {
console.log('Effect triggered');
}, [data]);
return <div>Check the console</div>;
};
export default DeepCompareEffectComponent;
useDefault
The useDefault
hook provides a way to set a default value for a state variable if it becomes undefined.
import React, { useState } from 'react';
import { useDefault } from 'react-use';
const DefaultComponent: React.FC = () => {
const [value, setValue] = useState<string | undefined>(undefined);
const defaultValue = useDefault(value, 'default');
return (
<div>
<p>Value: {defaultValue}</p>
<button onClick={() => setValue('new value')}>Set Value</button>
<button onClick={() => setValue(undefined)}>Reset</button>
</div>
);
};
export default DefaultComponent;
useDrop
The useDrop
hook simplifies handling drag-and-drop interactions by providing a ref and state for managing dropped files.
import React from 'react';
import { useDrop } from 'react-use';
const DropComponent: React.FC = () => {
const [ref, state] = useDrop({
onFiles: (files) => console.log(files),
});
return <div ref={ref}>Drop files here</div>;
};
export default DropComponent;
useEffectOnce
The useEffectOnce
hook runs an effect only once when the component mounts, similar to componentDidMount
in class components.
import React from 'react';
import { useEffectOnce } from 'react-use';
const EffectOnceComponent: React.FC = () => {
useEffectOnce(() => {
console.log('Effect runs once');
});
return <div>Check the console</div>;
};
export default EffectOnceComponent;
useEnsuredForwardedRef
The useEnsuredForwardedRef
hook ensures that a forwarded ref is always available, even if the parent component does not provide one.
import React, { forwardRef } from 'react';
import { useEnsuredForwardedRef } from 'react-use';
const EnsuredForwardedRefComponent = forwardRef<HTMLDivElement>((props, ref) => {
const ensuredRef = useEnsuredForwardedRef(ref);
return <div ref={ensuredRef}>Forwarded Ref</div>;
});
export default EnsuredForwardedRefComponent;
useError
The useError
hook provides a way to manage and throw errors within a component.
import React from 'react';
import { useError } from 'react-use';
const ErrorComponent: React.FC = () => {
const throwError = useError();
return (
<div>
<button onClick={() => throwError(new Error('Something went wrong!'))}>
Throw Error
</button>
</div>
);
};
export default ErrorComponent;
useEvent
The useEvent
hook allows you to attach and detach event listeners in a declarative way.
import React, { useState } from 'react';
import { useEvent } from 'react-use';
const EventComponent: React.FC = () => {
const [count, setCount] = useState(0);
useEvent('click', () => setCount((prev) => prev + 1), document);
return <div>Document Click Count: {count}</div>;
};
export default EventComponent;
useFavicon
The useFavicon
hook lets you dynamically change the favicon of your web application.
import React from 'react';
import { useFavicon } from 'react-use';
const FaviconComponent: React.FC = () => {
useFavicon('https://www.example.com/favicon.ico');
return <div>Check the favicon!</div>;
};
export default FaviconComponent;
useFirstMountState
The useFirstMountState
hook returns a boolean indicating whether the component is being mounted for the first time.
import React from 'react';
import { useFirstMountState } from 'react-use';
const FirstMountComponent: React.FC = () => {
const isFirstMount = useFirstMountState();
return <div>Is First Mount: {isFirstMount ? 'Yes' : 'No'}</div>;
};
export default FirstMountComponent;
useFullscreen
The useFullscreen
hook provides a way to enter and exit fullscreen mode for a specified element.
import React, { useRef } from 'react';
import { useFullscreen } from 'react-use';
const FullscreenComponent: React.FC = () => {
const ref = useRef(null);
const [isFullscreen, toggleFullscreen] = useFullscreen(ref);
return (
<div>
<div ref={ref}>Fullscreen Element</div>
<button onClick={toggleFullscreen}>
{isFullscreen ? 'Exit Fullscreen' : 'Enter Fullscreen'}
</button>
</div>
);
};
export default FullscreenComponent;
useGeolocation
The useGeolocation
hook provides the user’s current geolocation coordinates.
import React from 'react';
import { useGeolocation } from 'react-use';
const GeolocationComponent: React.FC = () => {
const state = useGeolocation();
return (
<div>
<p>Latitude: {state.latitude}</p>
<p>Longitude: {state.longitude}</p>
</div>
);
};
export default GeolocationComponent;
useGetSet
The useGetSet
hook provides a way to get and set state without causing a re-render.
import React from 'react';
import { useGetSet } from 'react-use';
const GetSetComponent: React.FC = () => {
const [getCount, setCount] = useGetSet(0);
return (
<div>
<button onClick={() => setCount(getCount() + 1)}>Increment</button>
<p>Count: {getCount()}</p>
</div>
);
};
export default GetSetComponent;
useGetSetState
The useGetSetState
hook provides a way to manage component state with get and set functions.
import React from 'react';
import { useGetSetState } from 'react-use';
const GetSetStateComponent: React.FC = () => {
const [getState, setState] = useGetSetState({ count: 0 });
return (
<div>
<button onClick={() => setState({ count: getState().count + 1 })}>
Increment
</button>
<p>Count: {getState().count}</p>
</div>
);
};
export default GetSetStateComponent;
useHarmonicIntervalFn
The useHarmonicIntervalFn
hook allows you to run a function at a harmonic interval, which can be useful for animations or repeated tasks that need to be in sync with the browser’s refresh rate.
import React, { useState } from 'react';
import { useHarmonicIntervalFn } from 'react-use';
const HarmonicIntervalComponent: React.FC = () => {
const [count, setCount] = useState(0);
useHarmonicIntervalFn(() => {
setCount((prev) => prev + 1);
}, 1000);
return <div>Count: {count}</div>;
};
export default HarmonicIntervalComponent;
useHash
The useHash
hook provides a way to manage the URL hash, allowing you to read and update it.
import React from 'react';
import { useHash } from 'react-use';
const HashComponent: React.FC = () => {
const [hash, setHash] = useHash();
return (
<div>
<p>Current Hash: {hash}</p>
<button onClick={() => setHash('new-hash')}>Set Hash</button>
</div>
);
};
export default HashComponent;
useHover
The useHover
hook allows you to detect whether an element is being hovered over.
import React, { useRef } from 'react';
import { useHover } from 'react-use';
const HoverComponent: React.FC = () => {
const elementRef = useRef(null);
const isHovered = useHover(elementRef);
return (
<div ref={elementRef}>
{isHovered ? 'Hovering!' : 'Not Hovering'}
</div>
);
};
export default HoverComponent;
useIdle
The useIdle
hook detects when the user becomes idle (inactive) for a specified period.
import React from 'react';
import { useIdle } from 'react-use';
const IdleComponent: React.FC = () => {
const isIdle = useIdle(3000); // 3 seconds
return <div>User is {isIdle ? 'Idle' : 'Active'}</div>;
};
export default IdleComponent;
useIntersection
The useIntersection
hook provides an easy way to observe when an element enters or leaves the viewport.
import React, { useRef } from 'react';
import { useIntersection } from 'react-use';
const IntersectionComponent: React.FC = () => {
const ref = useRef(null);
const intersection = useIntersection(ref, { rootMargin: '0px' });
return (
<div ref={ref}>
{intersection && intersection.isIntersecting ? 'In View' : 'Out of View'}
</div>
);
};
export default IntersectionComponent;
useInterval
The useInterval
hook allows you to run a function at specified intervals, similar to setInterval
.
import React, { useState } from 'react';
import { useInterval } from 'react-use';
const IntervalComponent: React.FC = () => {
const [count, setCount] = useState(0);
useInterval(() => {
setCount((prev) => prev + 1);
}, 1000);
return <div>Count: {count}</div>;
};
export default IntervalComponent;
useIsomorphicLayoutEffect
The useIsomorphicLayoutEffect
hook is a variant of useLayoutEffect
that works with server-side rendering.
import React from 'react';
import { useIsomorphicLayoutEffect } from 'react-use';
const IsomorphicLayoutEffectComponent: React.FC = () => {
useIsomorphicLayoutEffect(() => {
console.log('Effect runs');
}, []);
return <div>Check the console</div>;
};
export default IsomorphicLayoutEffectComponent;
useKey
The useKey
hook allows you to handle keyboard events for specific keys.
import React, { useState } from 'react';
import { useKey } from 'react-use';
const KeyComponent: React.FC = () => {
const [count, setCount] = useState(0);
useKey('ArrowUp', () => setCount((prev) => prev + 1));
return <div>Count: {count}</div>;
};
export default KeyComponent;
useKeyboardJs
The useKeyboardJs
hook provides a way to manage keyboard shortcuts using the keyboardjs
library.
import React, { useState } from 'react';
import { useKeyboardJs } from 'react-use';
const KeyboardJsComponent: React.FC = () => {
const [isPressed] = useKeyboardJs('ctrl + s');
return <div>Ctrl + S is {isPressed ? 'Pressed' : 'Not Pressed'}</div>;
};
export default KeyboardJsComponent;
useKeyPress
The useKeyPress
hook allows you to detect when a specific key is pressed.
import React from 'react';
import { useKeyPress } from 'react-use';
const KeyPressComponent: React.FC = () => {
const isEnterPressed = useKeyPress('Enter');
return <div>Enter is {isEnterPressed ? 'Pressed' : 'Not Pressed'}</div>;
};
export default KeyPressComponent;
useKeyPressEvent
The useKeyPressEvent
hook provides a way to handle key press events with ease.
import React, { useState } from 'react';
import { useKeyPressEvent } from 'react-use';
const KeyPressEventComponent: React.FC = () => {
const [key, setKey] = useState('');
useKeyPressEvent('Enter', () => setKey('Enter'));
return <div>Last Key Pressed: {key}</div>;
};
export default KeyPressEventComponent;
useLatest
The useLatest
hook returns the latest value of a variable, ensuring you always have the most recent reference.
import React, { useState } from 'react';
import { useLatest } from 'react-use';
const LatestComponent: React.FC = () => {
const [count, setCount] = useState(0);
const latestCount = useLatest(count);
return (
<div>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
<p>Latest Count: {latestCount.current}</p>
</div>
);
};
export default LatestComponent;
useLifecycles
The useLifecycles
hook provides a way to run functions on component mount and unmount.
import React from 'react';
import { useLifecycles } from 'react-use';
const LifecyclesComponent: React.FC = () => {
useLifecycles(
() => console.log('Mounted'),
() => console.log('Unmounted')
);
return <div>Check the console</div>;
};
export default LifecyclesComponent;
useList
The useList
hook provides a convenient way to manage an array of items with functions to manipulate the list.
import React from 'react';
import { useList } from 'react-use';
const ListComponent: React.FC = () => {
const [list, { push, removeAt }] = useList<number>([1, 2, 3]);
return (
<div>
<button onClick={() => push(list.length + 1)}>Add Item</button>
<button onClick={() => removeAt(0)}>Remove First Item</button>
<ul>
{list.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};
export default ListComponent;
useLocalStorage
The useLocalStorage
hook allows you to persist state in the browser’s local storage.
import React from 'react';
import { useLocalStorage } from 'react-use';
const LocalStorageComponent: React.FC = () => {
const [value, setValue] = useLocalStorage<string>('my-key', 'initial');
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} />
</div>
);
};
export default LocalStorageComponent;
useLocation
The useLocation
hook provides information about the current URL location.
import React from 'react';
import { useLocation } from 'react-use';
const LocationComponent: React.FC = () => {
const location = useLocation();
return (
<div>
<p>Pathname: {location.pathname}</p>
<p>Search: {location.search}</p>
</div>
);
};
export default LocationComponent;
useLockBodyScroll
The useLockBodyScroll
hook prevents the body from scrolling, useful for modals or sidebars.
import React from 'react';
import { useLockBodyScroll } from 'react-use';
const LockBodyScrollComponent: React.FC = () => {
useLockBodyScroll();
return <div>Body scroll is locked</div>;
};
export default LockBodyScrollComponent;
useLogger
The useLogger
hook logs the component’s props and state to the console, useful for debugging.
import React, { useState } from 'react';
import { useLogger } from 'react-use';
const LoggerComponent: React.FC = () => {
const [count, setCount] = useState(0);
useLogger('LoggerComponent', { count });
return (
<div>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
<p>Count: {count}</p>
</div>
);
};
export default LoggerComponent;
useLongPress
The useLongPress
hook detects long press gestures on an element.
import React from 'react';
import { useLongPress } from 'react-use';
const LongPressComponent: React.FC = () => {
const onLongPress = () => alert('Long Pressed!');
const longPressEvent = useLongPress(onLongPress, { delay: 500 });
return <button {...longPressEvent}>Long Press Me</button>;
};
export default LongPressComponent;
useMap
The useMap
hook provides a way to manage a map-like state with functions to manipulate it.
import React from 'react';
import { useMap } from 'react-use';
const MapComponent: React.FC = () => {
const [map, { set, remove, reset }] = useMap<string, number>([['key1', 1]]);
return (
<div>
<button onClick={() => set('key2', 2)}>Add Key2</button>
<button onClick={() => remove('key1')}>Remove Key1</button>
<button onClick={reset}>Reset</button>
<pre>{JSON.stringify(Array.from(map.entries()), null, 2)}</pre>
</div>
);
};
export default MapComponent;
useMeasure
The useMeasure
hook provides a way to measure the dimensions and position of an element.
import React, { useRef } from 'react';
import { useMeasure } from 'react-use';
const MeasureComponent: React.FC = () => {
const ref = useRef(null);
const rect = useMeasure(ref);
return (
<div ref={ref}>
<p>Width: {rect.width}</p>
<p>Height: {rect.height}</p>
</div>
);
};
export default MeasureComponent;
useMedia
The useMedia
hook allows you to query media features, such as screen size or orientation.
import React from 'react';
import { useMedia } from 'react-use';
const MediaComponent: React.FC = () => {
const isWide = useMedia('(min-width: 600px)');
return <div>Screen is {isWide ? 'Wide' : 'Narrow'}</div>;
};
export default MediaComponent;
useMediaDevices
The useMediaDevices
hook provides information about the user’s media devices, such as cameras and microphones.
import React from 'react';
import { useMediaDevices } from 'react-use';
const MediaDevicesComponent: React.FC = () => {
const devices = useMediaDevices();
return (
<div>
<p>Video Input Devices: {devices.videoInput.length}</p>
<p>Audio Input Devices: {devices.audioInput.length}</p>
</div>
);
};
export default MediaDevicesComponent;
useMediatedState
The useMediatedState
hook allows you to create a state that is mediated by a function, useful for derived state.
import React from 'react';
import { useMediatedState } from 'react-use';
const MediatedStateComponent: React.FC = () => {
const [state, setState] = useMediatedState<number, string>(
(value) => parseInt(value, 10),
'0'
);
return (
<div>
<input value={state.toString()} onChange={(e) => setState(e.target.value)} />
<p>Parsed Number: {state}</p>
</div>
);
};
export default MediatedStateComponent;
useMethods
The useMethods
hook provides a way to create a state with methods that can manipulate it.
import React from 'react';
import { useMethods } from 'react-use';
const methods = (state: number) => ({
increment: () => state + 1,
decrement: () => state - 1,
});
const MethodsComponent: React.FC = () => {
const [state, { increment, decrement }] = useMethods(methods, 0);
return (
<div>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<p>State: {state}</p>
</div>
);
};
export default MethodsComponent;
useMotion
The useMotion
hook provides information about the device’s motion, such as acceleration and rotation.
import React from 'react';
import { useMotion } from 'react-use';
const MotionComponent: React.FC = () => {
const motion = useMotion();
return (
<div>
<p>Acceleration: {JSON.stringify(motion.acceleration)}</p>
<p>Rotation: {JSON.stringify(motion.rotationRate)}</p>
</div>
);
};
export default MotionComponent;
useMount
The useMount
hook runs a function once when the component mounts.
import React from 'react';
import { useMount } from 'react-use';
const MountComponent: React.FC = () => {
useMount(() => {
console.log('Component mounted');
});
return <div>Check the console</div>;
};
export default MountComponent;
useMountedState
The useMountedState
hook returns a function that indicates whether the component is currently mounted.
import React, { useEffect } from 'react';
import { useMountedState } from 'react-use';
const MountedStateComponent: React.FC = () => {
const isMounted = useMountedState();
useEffect(() => {
console.log('Mounted:', isMounted());
}, []);
return <div>Check the console</div>;
};
export default MountedStateComponent;
useMouse
The useMouse
hook provides the current mouse position relative to an element.
import React, { useRef } from 'react';
import { useMouse } from 'react-use';
const MouseComponent: React.FC = () => {
const ref = useRef(null);
const { docX, docY } = useMouse(ref);
return (
<div ref={ref}>
<p>Mouse X: {docX}</p>
<p>Mouse Y: {docY}</p>
</div>
);
};
export default MouseComponent;
useMouseWheel
The useMouseWheel
hook provides information about the mouse wheel’s movement.
import React from 'react';
import { useMouseWheel } from 'react-use';
const MouseWheelComponent: React.FC = () => {
const { x, y } = useMouseWheel();
return (
<div>
<p>Wheel X: {x}</p>
<p>Wheel Y: {y}</p>
</div>
);
};
export default MouseWheelComponent;
useMultiStateValidator
The useMultiStateValidator
hook allows you to validate multiple states with a custom validation function.
import React, { useState } from 'react';
import { useMultiStateValidator } from 'react-use';
const MultiStateValidatorComponent: React.FC = () => {
const [value1, setValue1] = useState('');
const [value2, setValue2] = useState('');
const [isValid] = useMultiStateValidator(
[value1, value2],
(v1, v2) => v1.length > 0 && v2.length > 0
);
return (
<div>
<input value={value1} onChange={(e) => setValue1(e.target.value)} />
<input value={value2} onChange={(e) => setValue2(e.target.value)} />
<p>{isValid ? 'Valid' : 'Invalid'}</p>
</div>
);
};
export default MultiStateValidatorComponent;
useNetworkState
The useNetworkState
hook provides information about the current network status, such as whether the device is online or offline.
import React from 'react';
import { useNetworkState } from 'react-use';
const NetworkStateComponent: React.FC = () => {
const state = useNetworkState();
return (
<div>
<p>Online: {state.online ? 'Yes' : 'No'}</p>
<p>Since: {state.since?.toString()}</p>
</div>
);
};
export default NetworkStateComponent;
useObservable
The useObservable
hook allows you to subscribe to an observable and get its latest value.
import React from 'react';
import { useObservable } from 'react-use';
import { fromEvent } from 'rxjs';
const ObservableComponent: React.FC = () => {
const clicks = useObservable(fromEvent(document, 'click'));
return <div>Click anywhere!</div>;
};
export default ObservableComponent;
useOrientation
The useOrientation
hook provides information about the current screen orientation.
import React from 'react';
import { useOrientation } from 'react-use';
const OrientationComponent: React.FC = () => {
const { angle, type } = useOrientation();
return (
<div>
<p>Angle: {angle}</p>
<p>Type: {type}</p>
</div>
);
};
export default OrientationComponent;
usePageLeave
The usePageLeave
hook detects when the mouse leaves the page, which can be useful for showing exit-intent popups.
import React from 'react';
import { usePageLeave } from 'react-use';
const PageLeaveComponent: React.FC = () => {
usePageLeave(() => alert('Please don’t leave!'));
return <div>Move your mouse out of the page</div>;
};
export default PageLeaveComponent;
usePermission
The usePermission
hook provides a way to query the status of a browser permission.
import React from 'react';
import { usePermission } from 'react-use';
const PermissionComponent: React.FC = () => {
const state = usePermission({ name: 'geolocation' });
return <div>Geolocation Permission: {state}</div>;
};
export default PermissionComponent;
usePinchZoom
The usePinchZoom
hook allows you to implement pinch-to-zoom functionality on an element.
import React, { useRef } from 'react';
import { usePinchZoom } from 'react-use';
const PinchZoomComponent: React.FC = () => {
const ref = useRef(null);
usePinchZoom(ref);
return <div ref={ref}>Pinch to zoom this element</div>;
};
export default PinchZoomComponent;
usePrevious
The usePrevious
hook returns the previous value of a state or prop.
import React, { useState } from 'react';
import { usePrevious } from 'react-use';
const PreviousComponent: React.FC = () => {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Current: {count}</p>
<p>Previous: {prevCount}</p>
</div>
);
};
export default PreviousComponent;
usePreviousDistinct
The usePreviousDistinct
hook returns the last distinct value of a state or prop.
import React, { useState } from 'react';
import { usePreviousDistinct } from 'react-use';
const PreviousDistinctComponent: React.FC = () => {
const [count, setCount] = useState(0);
const prevCount = usePreviousDistinct(count);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Current: {count}</p>
<p>Previous Distinct: {prevCount}</p>
</div>
);
};
export default PreviousDistinctComponent;
usePromise
The usePromise
hook allows you to work with promises in a React component, handling loading and error states.
import React from 'react';
import { usePromise } from 'react-use';
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
};
const PromiseComponent: React.FC = () => {
const { loading, error, value } = usePromise(fetchData);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Data: {JSON.stringify(value)}</div>;
};
export default PromiseComponent;
useQueue
The useQueue
hook provides a way to manage a queue of items with functions to manipulate it.
import React from 'react';
import { useQueue } from 'react-use';
const QueueComponent: React.FC = () => {
const [queue, { add, remove, clear }] = useQueue<number>();
return (
<div>
<button onClick={() => add(queue.length + 1)}>Add Item</button>
<button onClick={remove}>Remove Item</button>
<button onClick={clear}>Clear Queue</button>
<p>Queue: {queue.join(', ')}</p>
</div>
);
};
export default QueueComponent;
useRaf
The useRaf
hook provides a way to run a function on every animation frame.
import React, { useState } from 'react';
import { useRaf } from 'react-use';
const RafComponent: React.FC = () => {
const [count, setCount] = useState(0);
useRaf(() => {
setCount((prev) => prev + 1);
});
return <div>Count: {count}</div>;
};
export default RafComponent;
useRafLoop
The useRafLoop
hook allows you to run a function in a loop using requestAnimationFrame.
import React, { useState } from 'react';
import { useRafLoop } from 'react-use';
const RafLoopComponent: React.FC = () => {
const [count, setCount] = useState(0);
useRafLoop(() => {
setCount((prev) => prev + 1);
});
return <div>Count: {count}</div>;
};
export default RafLoopComponent;
useRafState
The useRafState
hook provides a way to update state only on animation frames, optimizing performance.
import React from 'react';
import { useRafState } from 'react-use';
const RafStateComponent: React.FC = () => {
const [state, setState] = useRafState(0);
return (
<div>
<button onClick={() => setState((prev) => prev + 1)}>Increment</button>
<p>State: {state}</p>
</div>
);
};
export default RafStateComponent;
useRendersCount
The useRendersCount
hook returns the number of times a component has rendered.
import React from 'react';
import { useRendersCount } from 'react-use';
const RendersCountComponent: React.FC = () => {
const rendersCount = useRendersCount();
return <div>Renders Count: {rendersCount}</div>;
};
export default RendersCountComponent;
useScratch
The useScratch
hook provides a way to track mouse movements on an element, useful for drawing or scratch-off effects.
import React, { useRef } from 'react';
import { useScratch } from 'react-use';
const ScratchComponent: React.FC = () => {
const ref = useRef(null);
const { isScratching, coords } = useScratch(ref);
return (
<div ref={ref}>
<p>Scratching: {isScratching ? 'Yes' : 'No'}</p>
<p>Coords: {JSON.stringify(coords)}</p>
</div>
);
};
export default ScratchComponent;
useScroll
The useScroll
hook provides information about the scroll position of an element.
import React, { useRef } from 'react';
import { useScroll } from 'react-use';
const ScrollComponent: React.FC = () => {
const ref = useRef(null);
const { x, y } = useScroll(ref);
return (
<div ref={ref}>
<p>Scroll X: {x}</p>
<p>Scroll Y: {y}</p>
</div>
);
};
export default ScrollComponent;
useScrollbarWidth
The useScrollbarWidth
hook returns the width of the scrollbar, useful for layout calculations.
import React from 'react';
import { useScrollbarWidth } from 'react-use';
const ScrollbarWidthComponent: React.FC = () => {
const scrollbarWidth = useScrollbarWidth();
return <div>Scrollbar Width: {scrollbarWidth}px</div>;
};
export default ScrollbarWidthComponent;
useScrolling
The useScrolling
hook detects if an element is currently being scrolled.
import React, { useRef } from 'react';
import { useScrolling } from 'react-use';
const ScrollingComponent: React.FC = () => {
const ref = useRef(null);
const isScrolling = useScrolling(ref);
return <div ref={ref}>Scrolling: {isScrolling ? 'Yes' : 'No'}</div>;
};
export default ScrollingComponent;
useSearchParam
The useSearchParam
hook provides a way to read and update URL search parameters.
import React from 'react';
import { useSearchParam } from 'react-use';
const SearchParamComponent: React.FC = () => {
const [param, setParam] = useSearchParam('query');
return (
<div>
<p>Search Param: {param}</p>
<button onClick={() => setParam('new-value')}>Set Param</button>
</div>
);
};
export default SearchParamComponent;
useSessionStorage
The useSessionStorage
hook allows you to persist state in the session storage.
import React from 'react';
import { useSessionStorage } from 'react-use';
const SessionStorageComponent: React.FC = () => {
const [value, setValue] = useSessionStorage<string>('my-key', 'initial');
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} />
</div>
);
};
export default SessionStorageComponent;
useSet
The useSet
hook provides a way to manage a set-like state with functions to manipulate it.
import React from 'react';
import { useSet } from 'react-use';
const SetComponent: React.FC = () => {
const [set, { add, remove, reset }] = useSet<number>();
return (
<div>
<button onClick={() => add(set.size + 1)}>Add Item</button>
<button onClick={() => remove(1)}>Remove Item</button>
<button onClick={reset}>Reset</button>
<p>Set: {Array.from(set).join(', ')}</p>
</div>
);
};
export default SetComponent;
useSetState
The useSetState
hook provides a way to manage a state object with partial updates.
import React from 'react';
import { useSetState } from 'react-use';
const SetStateComponent: React.FC = () => {
const [state, setState] = useSetState({ count: 0, text: '' });
return (
<div>
<button onClick={() => setState({ count: state.count + 1 })}>Increment</button>
<input value={state.text} onChange={(e) => setState({ text: e.target.value })} />
<p>Count: {state.count}</p>
<p>Text: {state.text}</p>
</div>
);
};
export default SetStateComponent;
useShallowCompareEffect
The useShallowCompareEffect
hook is a variant of useEffect
that performs a shallow comparison of dependencies.
import React, { useState } from 'react';
import { useShallowCompareEffect } from 'react-use';
const ShallowCompareEffectComponent: React.FC = () => {
const [data, setData] = useState({ key: 'value' });
useShallowCompareEffect(() => {
console.log('Effect triggered');
}, [data]);
return <div>Check the console</div>;
};
export default ShallowCompareEffectComponent;
useSize
The useSize
hook provides the dimensions of an element, updating when the element’s size changes.
import React, { useRef } from 'react';
import { useSize } from 'react-use';
const SizeComponent: React.FC = () => {
const ref = useRef(null);
const size = useSize(ref);
return (
<div ref={ref}>
<p>Width: {size.width}</p>
<p>Height: {size.height}</p>
</div>
);
};
export default SizeComponent;
useSlider
The useSlider
hook provides a way to implement a slider component with drag functionality.
import React, { useRef } from 'react';
import { useSlider } from 'react-use';
const SliderComponent: React.FC = () => {
const ref = useRef(null);
const { value } = useSlider(ref);
return (
<div ref={ref}>
<p>Slider Value: {value}</p>
</div>
);
};
export default SliderComponent;
useSpeech
The useSpeech
hook provides a way to use the Web Speech API for text-to-speech functionality.
import React from 'react';
import { useSpeech } from 'react-use';
const SpeechComponent: React.FC = () => {
const { speak, cancel } = useSpeech();
return (
<div>
<button onClick={() => speak('Hello world!')}>Speak</button>
<button onClick={cancel}>Cancel</button>
</div>
);
};
export default SpeechComponent;
useSpring
The useSpring
hook provides a way to create spring animations for numeric values.
import React from 'react';
import { useSpring } from 'react-use';
const SpringComponent: React.FC = () => {
const spring = useSpring(0, 100);
return <div>Spring Value: {spring}</div>;
};
export default SpringComponent;
useStartTyping
The useStartTyping
hook detects when the user starts typing on the keyboard.
import React from 'react';
import { useStartTyping } from 'react-use';
const StartTypingComponent: React.FC = () => {
const isTyping = useStartTyping();
return <div>Typing: {isTyping ? 'Yes' : 'No'}</div>;
};
export default StartTypingComponent;
useStateList
The useStateList
hook provides a way to manage a list of states with functions to navigate through them.
import React from 'react';
import { useStateList } from 'react-use';
const StateListComponent: React.FC = () => {
const [state, { next, prev }] = useStateList(['State 1', 'State 2', 'State 3']);
return (
<div>
<button onClick={prev}>Previous</button>
<button onClick={next}>Next</button>
<p>Current State: {state}</p>
</div>
);
};
export default StateListComponent;
useStateList
The useStateList
hook provides a way to manage a list of states with functions to navigate through them.
import React from 'react';
import { useStateList } from 'react-use';
const StateListComponent: React.FC = () => {
const [state, { next, prev }] = useStateList(['State 1', 'State 2', 'State 3']);
return (
<div>
<button onClick={prev}>Previous</button>
<button onClick={next}>Next</button>
<p>Current State: {state}</p>
</div>
);
};
export default StateListComponent;
useStateValidator
The useStateValidator
hook provides a way to validate a state variable with a custom validation function.
import React, { useState } from 'react';
import { useStateValidator } from 'react-use';
const StateValidatorComponent: React.FC = () => {
const [value, setValue] = useState('');
const [isValid] = useStateValidator(value, (v) => v.length > 3);
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<p>{isValid ? 'Valid' : 'Invalid'}</p>
</div>
);
};
export default StateValidatorComponent;
useStateWithHistory
The useStateWithHistory
hook allows you to manage state with a history, enabling undo and redo functionality.
import React from 'react';
import { useStateWithHistory } from 'react-use';
const StateWithHistoryComponent: React.FC = () => {
const [state, { set, back, forward, history }] = useStateWithHistory(0);
return (
<div>
<button onClick={() => set(state + 1)}>Increment</button>
<button onClick={back}>Undo</button>
<button onClick={forward}>Redo</button>
<p>Current State: {state}</p>
<p>History: {history.join(', ')}</p>
</div>
);
};
export default StateWithHistoryComponent;
useThrottle
The useThrottle
hook provides a way to throttle a value, ensuring it updates at most once every specified delay.
import React, { useState } from 'react';
import { useThrottle } from 'react-use';
const ThrottleComponent: React.FC = () => {
const [value, setValue] = useState('');
const throttledValue = useThrottle(value, 1000);
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<p>Throttled Value: {throttledValue}</p>
</div>
);
};
export default ThrottleComponent;
useThrottleFn
The useThrottleFn
hook allows you to throttle a function, ensuring it executes at most once every specified delay.
import React, { useState } from 'react';
import { useThrottleFn } from 'react-use';
const ThrottleFnComponent: React.FC = () => {
const [count, setCount] = useState(0);
const throttledIncrement = useThrottleFn(() => setCount((prev) => prev + 1), 1000);
return (
<div>
<button onClick={throttledIncrement}>Increment</button>
<p>Count: {count}</p>
</div>
);
};
export default ThrottleFnComponent;
useTimeout
The useTimeout
hook provides a way to execute a function after a specified delay.
import React, { useState } from 'react';
import { useTimeout } from 'react-use';
const TimeoutComponent: React.FC = () => {
const [count, setCount] = useState(0);
useTimeout(() => setCount((prev) => prev + 1), 2000);
return <div>Count: {count}</div>;
};
export default TimeoutComponent;
useTimeoutFn
The useTimeoutFn
hook provides a way to execute a function after a specified delay, with control over starting and stopping the timer.
import React, { useState } from 'react';
import { useTimeoutFn } from 'react-use';
const TimeoutFnComponent: React.FC = () => {
const [count, setCount] = useState(0);
const [isReady, cancel, reset] = useTimeoutFn(() => setCount((prev) => prev + 1), 2000);
return (
<div>
<button onClick={reset}>Reset Timer</button>
<button onClick={cancel}>Cancel Timer</button>
<p>Count: {count}</p>
<p>Is Ready: {isReady ? 'Yes' : 'No'}</p>
</div>
);
};
export default TimeoutFnComponent;
useTitle
The useTitle
hook allows you to set the document title.
import React from 'react';
import { useTitle } from 'react-use';
const TitleComponent: React.FC = () => {
useTitle('My Custom Title');
return <div>Check the document title</div>;
};
export default TitleComponent;
useToggle
The useToggle
hook provides a simple way to manage boolean state with a toggle function.
import React from 'react';
import { useToggle } from 'react-use';
const ToggleComponent: React.FC = () => {
const [isToggled, toggle] = useToggle(false);
return (
<div>
<button onClick={toggle}>{isToggled ? 'ON' : 'OFF'}</button>
</div>
);
};
export default ToggleComponent;
useTween
The useTween
hook provides a way to animate a value over time using a tweening function.
import React from 'react';
import { useTween } from 'react-use';
const TweenComponent: React.FC = () => {
const tween = useTween('linear', 1000);
return <div>Tween Value: {tween}</div>;
};
export default TweenComponent;
useUnmount
The useUnmount
hook runs a function when the component unmounts.
import React from 'react';
import { useUnmount } from 'react-use';
const UnmountComponent: React.FC = () => {
useUnmount(() => {
console.log('Component unmounted');
});
return <div>Check the console</div>;
};
export default UnmountComponent;
useUnmountPromise
The useUnmountPromise
hook provides a way to handle promises that should be canceled when the component unmounts.
import React from 'react';
import { useUnmountPromise } from 'react-use';
const UnmountPromiseComponent: React.FC = () => {
const unmountPromise = useUnmountPromise();
const fetchData = async () => {
const promise = fetch('https://api.example.com/data');
const response = await unmountPromise(promise);
console.log(await response.json());
};
return <button onClick={fetchData}>Fetch Data</button>;
};
export default UnmountPromiseComponent;
useUpdate
The useUpdate
hook provides a way to force a component to re-render.
import React from 'react';
import { useUpdate } from 'react-use';
const UpdateComponent: React.FC = () => {
const update = useUpdate();
return <button onClick={update}>Force Update</button>;
};
export default UpdateComponent;
useUpdateEffect
The useUpdateEffect
hook is similar to useEffect
, but it only runs when dependencies update, not on initial render.
import React, { useState } from 'react';
import { useUpdateEffect } from 'react-use';
const UpdateEffectComponent: React.FC = () => {
const [count, setCount] = useState(0);
useUpdateEffect(() => {
console.log('Count updated:', count);
}, [count]);
return <button onClick={() => setCount(count + 1)}>Increment</button>;
};
export default UpdateEffectComponent;
useUpsert
The useUpsert
hook provides a way to update or insert an item into an array based on a predicate.
import React from 'react';
import { useUpsert } from 'react-use';
const UpsertComponent: React.FC = () => {
const [items, upsert] = useUpsert<{ id: number; value: string }>((item) => item.id);
return (
<div>
<button onClick={() => upsert({ id: 1, value: 'Item 1' })}>Upsert Item 1</button>
<button onClick={() => upsert({ id: 2, value: 'Item 2' })}>Upsert Item 2</button>
<ul>
{items.map((item) => (
<li key={item.id}>{item.value}</li>
))}
</ul>
</div>
);
};
export default UpsertComponent;
useVibrate
The useVibrate
hook provides a way to use the Vibration API to vibrate the device.
import React from 'react';
import { useVibrate } from 'react-use';
const VibrateComponent: React.FC = () => {
const vibrate = useVibrate();
return <button onClick={() => vibrate([200, 100, 200])}>Vibrate</button>;
};
export default VibrateComponent;
useVideo
The useVideo
hook provides a way to manage video playback in a React component.
import React from 'react';
import { useVideo } from 'react-use';
const VideoComponent: React.FC = () => {
const [video, state, controls] = useVideo(
<video src="https://www.example.com/video.mp4" />
);
return (
<div>
{video}
<button onClick={controls.play}>Play</button>
<button onClick={controls.pause}>Pause</button>
</div>
);
};
export default VideoComponent;
useWindowScroll
The useWindowScroll
hook provides information about the window’s scroll position.
import React from 'react';
import { useWindowScroll } from 'react-use';
const WindowScrollComponent: React.FC = () => {
const { x, y } = useWindowScroll();
return (
<div>
<p>Scroll X: {x}</p>
<p>Scroll Y: {y}</p>
</div>
);
};
export default WindowScrollComponent;
useWindowSize
The useWindowSize
hook provides the dimensions of the window, updating when the window is resized.
import React from 'react';
import { useWindowSize } from 'react-use';
const WindowSizeComponent: React.FC = () => {
const { width, height } = useWindowSize();
return (
<div>
<p>Width: {width}</p>
<p>Height: {height}</p>
</div>
);
};
export default WindowSizeComponent;
Conclusion
The react-use library is a powerful tool for React developers, offering a wide range of hooks that simplify state management, side effects, and UI interactions. By incorporating react-use into your projects, you can streamline your development process and focus on building robust applications. Whether you’re a beginner or an experienced developer, react-use provides valuable utilities that can enhance your React applications.