Helpers and Hooks
Legend-State includes some helpful observables and hooks for common tasks. These are available at their own import paths so they don’t increase the size of your bundle unless you use them.
Helper observables
currentDate
currentDate
is an observable containing the current date (with no time) that changes automatically at midnight.
currentTime
currentTime
is an observable containing the current time that changes automatically every minute.
pageHash (web)
pageHash
is an observable that updates with the page hash, and changes the page hash when the observable is changed. Use configurePageHash
to control how it sets the page hash, with pushState | replaceState | location.hash
pageHashParams (web)
pageHashParams
is an observable that updates with the page hash, and changes the page hash when the observable is changed. Use configurePageHashParams
to control how it sets the page hash, with pushState | replaceState | location.hash
Hooks
useHover (web)
useHover
returns an observable whose value is true | false
based on whether the target element is hovered. This can be useful for using fine-grained reactivity features to update without re-rendering the component, or to pass the observable around to other components for them to consume it.
useIsMounted
useIsMounted
returns an observable whose value is true | false
based on whether the component is mounted. This can be useful in delayed or asynchronous functions to make sure it’s running an a component that’s still mounted.
useMeasure (web)
useMeasure
returns an observable whose value is the size ({ width: number, height: number }
) of the target element. It starts with undefined values that get set after initial mount, and whenever the element resizes.
One example of where this could be useful is to drive animations. This example measures the size of an inner element to animate a bottom sheet from the bottom to its height. It uses framer-motion and reactive to be able to drive animations with observable values.
createObservableHook
createObservableHook
is a helper to convert an existing hook to return an observable. It works by overriding useState
and useReducer
in the hopes of catching and converting them into observable sets. So it may work for some hooks and it may not. Please let us know on GitHub if it’s not working for some hooks.