standard-hooks 🎣
Essential set of React Hooks for convenient Web API consumption.
Key features
- 🌳 Bundler-friendly with tree shaking support
- 📚 Well-documented and type-safe interfaces
- ⚛️ Zero-config server-side rendering capability
- 📦 Self-contained, free of runtime dependencies
Sandbox
👉 Explore the API with working examples
Reference
Table of Contents
- Sensors
- useDeviceMotion
- useDeviceOrientation
- useDocumentReadiness
- useDocumentVisibility
- useGeolocation
- useMedia
- useMouseCoords
- useNetworkAvailability
- useNetworkInformation
- usePreferredColorScheme
- usePreferredLanguages
- useViewportScale
- useViewportScrollCoords
- useViewportSize
- useWindowScrollCoords
- useWindowSize
- Storage
- Scheduling
- State
Sensors
useDeviceMotion
Tracks acceleration and rotation rate of the device.
Examples
{ const acceleration rotationRate interval = ; // ...}
Returns EventArgs<DeviceMotionEvent> Own properties of the last corresponding event.
useDeviceOrientation
Tracks physical orientation of the device.
Examples
{ const alpha beta gamma = ; // ...}
Returns EventArgs<DeviceOrientationEvent> Own properties of the last corresponding event.
useDocumentReadiness
Tracks loading state of the page.
Examples
{ const documentReadiness = ; 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.
useDocumentVisibility
Tracks visibility of the page.
Examples
{ const documentVisibility = ; if documentVisibility === 'hidden' // Reduce resource utilization to aid background page performance // ...}
Returns VisibilityState Visibility state of the document
, which is 'visible'
by default.
useGeolocation
Tracks geolocation of the device.
Parameters
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.
Examples
{ const geolocation = ; if geolocation const coords = geolocation; // ...}
Returns (Position | undefined) Locational data, or undefined
when unavailable.
useMedia
Tracks match state of a media query.
Parameters
query
string Media query to parse.
Examples
{ const isWidescreen = ; // ...}
Returns boolean true
if the associated media query list matches the state of the document
, or false
otherwise.
useMouseCoords
Tracks mouse position.
Examples
{ const mouseX mouseY = ; // ...}
Returns Readonly<[number, number]> Coordinates [x, y]
, falling back to [0, 0]
when unavailable.
useNetworkAvailability
Tracks information about the network's availability.
⚠️ This attribute is inherently unreliable. A computer can be connected to a network without having internet access.
Examples
{ const isOnline = ; // ...}
Returns boolean false
if the user agent is definitely offline, or true
if it might be online.
useNetworkInformation
Tracks information about the device's network connection.
⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.
Examples
{ const networkInformation = ; if networkInformation const effectiveType downlink rtt saveData = networkInformation; // ...}
Returns (NetworkInformation | undefined) Connection data, or undefined
when unavailable.
usePreferredColorScheme
Tracks color scheme preference of the user.
Examples
{ const preferredColorScheme = ; const isDarkMode = === 'dark'; // ...}
Returns ("no-preference"
| "light"
| "dark"
) Preferred color scheme.
usePreferredLanguages
Tracks language preferences of the user.
Examples
{ const preferredLanguages = ; // ...}
Returns ReadonlyArray<string> An array of BCP 47 language tags, ordered by preference with the most preferred language first.
useViewportScale
Tracks visual viewport scale.
⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.
Examples
{ const viewportScale = ; // ...}
Returns number Pinch-zoom scaling factor, falling back to 0
when unavailable.
useViewportScrollCoords
Tracks visual viewport scroll position.
⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.
Examples
{ const viewportScrollX viewportScrollY = ; // ...}
Returns Readonly<[number, number]> Coordinates [x, y]
, falling back to [0, 0]
when unavailable.
useViewportSize
Tracks visual viewport size.
⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.
Examples
{ const viewportWidth viewportHeight = ; // ...}
Returns Readonly<[number, number]> Dimensions [width, height]
, falling back to [0, 0]
when unavailable.
useWindowScrollCoords
Tracks window scroll position.
Examples
{ const windowScrollX windowScrollY = ; // ...}
Returns Readonly<[number, number]> Coordinates [x, y]
, falling back to [0, 0]
when unavailable.
useWindowSize
Tracks window size.
Examples
{ const windowWidth windowHeight = ; // ...}
Returns Readonly<[number, number]> Dimensions [width, height]
, falling back to [0, 0]
when unavailable.
Storage
useLocalStorage
- See:
useState
hook, which exposes a similar interface
Stores a key/value pair statefully in localStorage
.
Parameters
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.
Examples
{ const visitCount setVisitCount = useLocalStorage < number > 'visitCount' 0; ; // ...}
Returns [T, React.Dispatch<React.SetStateAction<T>>] A statefully stored value, and a function to update it.
useSessionStorage
- See:
useState
hook, which exposes a similar interface
Stores a key/value pair statefully in sessionStorage
.
Parameters
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.
Examples
{ const name setName = useSessionStorage < string > 'name' 'Anonymous'; // ...}
Returns [T, React.Dispatch<React.SetStateAction<T>>] A statefully stored value, and a function to update it.
Scheduling
useEventListener
Listens to an event while the enclosing component is mounted.
Parameters
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.
Examples
{ ; // ...}
useInterval
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.
Parameters
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.
Examples
{ ; // ...}
State
usePrevious
Tracks previous state of a value.
Parameters
value
T Props, state or any other calculated value.
Examples
{ const count setCount = ; const prevCount = ; // ... return `Now: , before: `;}
Returns (T | undefined) Value from the previous render of the enclosing component.
useTimeline
Records states of a value over time.
Parameters
value
T Props, state or any other calculated value.maxLength
number Maximum amount of states to store at once. Should be an integer greater than 1. (optional, defaultMAX_ARRAY_INDEX
)
Examples
{ const count setCount = ; const counts = ; // ... return `Now: , history: `;}
Returns ReadonlyArray<T> Results of state updates in chronological order.
useToggle
- See:
useState
hook, which exposes a similar interface
Tracks state of a boolean value.
Parameters
initialValue
boolean Initial value. (optional, defaultfalse
)
Examples
{ const isPressed togglePressed = ; // ... 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.
useUndoable
Wraps a state hook to add undo/redo functionality.
Parameters
useStateResult
[T, React.Dispatch<React.SetStateAction<T>>] Return value of a state hook.useStateResult.0
Current state.useStateResult.1
State updater function.
maxDeltas
number Maximum amount of state differences to store at once. Should be a positive integer. (optional, defaultMAX_SMALL_INTEGER
)
Examples
{ const value setValue undo redo pastValues futureValues = ; // ... return <> <button type="button" onClick=undo disabled=pastValueslength === 0> Undo </button> <input value=value onChange= /> <button type="button" onClick=redo disabled=futureValueslength === 0> Redo </button> </> ;}
Returns [T, React.Dispatch<React.SetStateAction<T>>, function (): void, function (): void, Array<T>, Array<T>] State hook result extended with undo
, redo
, pastValues
and futureValues
.
Performance tips
-
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.:;
Contributing
Thanks for being interested in contributing! Please read our contribution guidelines to get started.
Contributors ✨
Thanks goes to these wonderful people (emoji key):
Kristóf Poduszló 🚧 💻 ⚠️ 📖 💡 🤔 🚇 |
Dan Abramov 💻 📝 🤔 ✅ |
Donavon West ⚠️ |
Prasanna Mishra 📖 |
Nolansym 💡 |
Charles Moog 💻 ⚠️ 📖 💡 |
Michael Jackson 🤔 |
This project follows the all-contributors specification. Contributions of any kind welcome!