Essential set of React Hooks for convenient Web API consumption.
- 🌳 Bundler-friendly with tree shaking support
- 📚 Well-documented and type-safe interfaces
- ⚛️ Zero-config server-side rendering capability
- 📦 Self-contained, free of runtime dependencies
👉 Explore the API with working examples
Tracks acceleration and rotation rate of the device.
function Example() {
const { acceleration, rotationRate, interval } = useDeviceMotion();
// ...
}
Returns EventArgs<DeviceMotionEvent> Own properties of the last corresponding event.
Tracks physical orientation of the device.
function Example() {
const { alpha, beta, gamma } = useDeviceOrientation();
// ...
}
Returns EventArgs<DeviceOrientationEvent> Own properties of the last corresponding event.
Tracks loading state of the page.
function Example() {
const documentReadiness = useDocumentReadiness();
if (documentReadiness === 'interactive') {
// You may interact with any element of the document from now
}
// ...
}
Returns DocumentReadyState Readiness of the document
, which is 'loading'
by default.
Tracks visibility of the page.
function Example() {
const documentVisibility = useDocumentVisibility();
if (documentVisibility === 'hidden') {
// Reduce resource utilization to aid background page performance
}
// ...
}
Returns VisibilityState Visibility state of the document
, which is 'visible'
by default.
Tracks geolocation of the device.
options
PositionOptions? Additional watching options.errorCallback
function (error: PositionError): void? Method to execute in case of an error, e.g. when the user denies location sharing permissions.
function Example() {
const geolocation = useGeolocation();
if (geolocation) {
const { coords } = geolocation;
}
// ...
}
Returns (Position | undefined) Locational data, or undefined
when unavailable.
Tracks match state of a media query.
query
string Media query to parse.
function Example() {
const isWidescreen = useMedia('(min-aspect-ratio: 16/9)');
// ...
}
Returns boolean true
if the associated media query list matches the state of the document
, or false
otherwise.
Tracks mouse position.
function Example() {
const [mouseX, mouseY] = useMouseCoords();
// ...
}
Returns Readonly<[number, number]> Coordinates [x, y]
, falling back to [0, 0]
when unavailable.
Tracks information about the network's availability.
function Example() {
const isOnline = useNetworkAvailability();
// ...
}
Returns boolean false
if the user agent is definitely offline, or true
if it might be online.
Tracks information about the device's network connection.
⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.
function Example() {
const networkInformation = useNetworkInformation();
if (networkInformation) {
const { effectiveType, downlink, rtt, saveData } = networkInformation;
}
// ...
}
Returns (NetworkInformation | undefined) Connection data, or undefined
when unavailable.
Tracks color scheme preference of the user.
function Example() {
const preferredColorScheme = usePreferredColorScheme();
const isDarkMode = usePreferredColorScheme() === 'dark';
// ...
}
Returns ("no-preference"
| "light"
| "dark"
) Preferred color scheme.
Tracks language preferences of the user.
function Example() {
const preferredLanguages = usePreferredLanguages();
// ...
}
Returns ReadonlyArray<string> An array of BCP 47 language tags, ordered by preference with the most preferred language first.
Tracks window scroll position.
function Example() {
const [windowScrollX, windowScrollY] = useWindowScrollCoords();
// ...
}
Returns Readonly<[number, number]> Coordinates [x, y]
, falling back to [0, 0]
when unavailable.
Tracks window size.
function Example() {
const [windowWidth, windowHeight] = useWindowSize();
// ...
}
Returns Readonly<[number, number]> Dimensions [width, height]
, falling back to [0, 0]
when unavailable.
- See:
useState
hook, which exposes a similar interface
Stores a key/value pair statefully in localStorage
.
key
string Identifier to associate the stored value with.initialValue
(T | function (): T | null) Value used when no item exists with the given key. Lazy initialization is available by using a function which returns the desired value. (optional, defaultnull
)errorCallback
function (error: (DOMException | TypeError)): void? Method to execute in case of an error, e.g. when the storage quota has been exceeded or trying to store a circular data structure.
function Example() {
const [visitCount, setVisitCount] =
useLocalStorage < number > ('visitCount', 0);
useEffect(() => {
setVisitCount(count => count + 1);
}, []);
// ...
}
Returns [T, React.Dispatch<React.SetStateAction<T>>] A statefully stored value, and a function to update it.
- See:
useState
hook, which exposes a similar interface
Stores a key/value pair statefully in sessionStorage
.
key
string Identifier to associate the stored value with.initialValue
(T | function (): T | null) Value used when no item exists with the given key. Lazy initialization is available by using a function which returns the desired value. (optional, defaultnull
)errorCallback
function (error: (DOMException | TypeError)): void? Method to execute in case of an error, e.g. when the storage quota has been exceeded or trying to store a circular data structure.
function Example() {
const [name, setName] = useSessionStorage < string > ('name', 'Anonymous');
// ...
}
Returns [T, React.Dispatch<React.SetStateAction<T>>] A statefully stored value, and a function to update it.
Listens to an event while the enclosing component is mounted.
target
EventTarget Target to listen on, possibly a DOM element or a remote service connector.type
string Name of event (case-sensitive).callback
EventListener Method to execute whenever the event fires.options
AddEventListenerOptions? Additional listener characteristics.
function Example() {
useEventListener(window, 'error', () => {
console.log('A resource failed to load.');
});
// ...
}
Repeatedly calls a function with a fixed time delay between each call.
📝 Timings may be inherently inaccurate, due to the implementation of setInterval
under the hood.
callback
function (): void Method to execute periodically.delayMs
(number | null) Time, in milliseconds, to wait between executions of the specified function. Set tonull
for pausing.
function Example() {
useInterval(() => {
// Custom logic to execute each second
}, 1000);
// ...
}
Tracks previous state of a value.
value
T Props, state or any other calculated value.
function Example() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
// ...
return `Now: ${count}, before: ${prevCount}`;
}
Returns T Value from the previous render of the enclosing component.
Records states of a value over time.
value
T Props, state or any other calculated value.maxLength
number Maximum amount of states to store. Should be an integer more than 1. (optional, defaultMAX_ARRAY_INDEX
)
function Example() {
const [count, setCount] = useState(0);
const counts = useTimeline(count);
// ...
return `Now: ${count}, history: ${counts}`;
}
Returns ReadonlyArray<T> Results of state updates in chronological order.
- See:
useState
hook, which exposes a similar interface
Tracks state of a boolean value.
initialValue
boolean Initial value. (optional, defaultfalse
)
function Example() {
const [isPressed, togglePressed] = useToggle();
// ...
return (
<button type="button" aria-pressed={isPressed} onClick={togglePressed}>
Toggle state
</button>
);
}
Returns [boolean, function (nextValue: boolean?): void] A statefully stored value, and a function to update it. The latter may be called without a boolean argument to negate the value.
-
Avoid layout thrashing by debouncing or throttling high frequency events, e.g. scrolling or mouse movements
-
Move non-primitive hook parameters to an outer scope or memoize them with
useMemo
, e.g.:const geolocationOptions = { enableHighAccuracy: true }; function Example() { const geolocation = useGeolocation(geolocationOptions); // ... }
Thanks for being interested in contributing! Please read our contribution guidelines to get started.
Thanks goes to these wonderful people (emoji key):
Kristóf Poduszló 🚧 💻 |
Dan Abramov 💻 📝 🤔 ✅ |
Donavon West |
Prasanna Mishra 📖 |
Nolansym 💡 |
Charles Moog 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!