Essential hooks collection for everyday react1 projects.
Principles
1. Framework agnostic
Unihooks are not bound to react and work with any hooks-enabled framework:
See any-hooks for the full list.
2. Unified
Unihooks follow useState
signature for intuitivity.
let state actions =
3. Essential
Unihooks deliver value in reactive context, they're not mere wrappers for native API. Static hooks are avoided.
const MyComponent = { let ua = } // ✘ − user agent never changesconst MyComponent = { let ua = navigatoruserAgent } // ✔ − direct API must be used instead
Hooks
useChannel
[value, setValue] = useChannel(key, init?, deps?)
Global value provider - useState
with value identified globally by key
.
Can be used as value store, eg. as application model layer without persistency. Also can be used for intercomponent communication.
init
can be a value or a function, and (re)applies if the key
(or deps
) changes.
{ let users setUsers = // or as reducer }
useStorage
[value, setValue] = useStorage(key, init?, options?)
useChannel
with persistency to local/session storage. Subscribes to storage
event - updates if storage is changed from another tab.
{ const count setCount = } { const count setCount = // count === 1 // (↑ updates Component1 too)} { const count setCount = }
options
prefix
- prefix that's added to stored keys.storage
- manually pass session/local/etc storage.
Reference: useStore.
useAction
[action] = useAction(key, cb, deps?)
Similar to useChannel
, but used for storing functions. Different from useChannel
in the same way the useCallback
is different from useMemo
. deps
indicate if value must be reinitialized.
{ } { let content setContent = let load = return html` `}
useSearchParam
[value, setValue] = useSearchParam(name, init?)
Reflect value to location.search
. value
is turned to string via URLSearchParams.
To serialize objects or arrays, provide .toString
method or convert manually.
NOTE. Patches history.push
and history.replace
to enable pushstate
and replacestate
events.
{ let id setId = }
useCountdown
[n, reset] = useCountdown(startValue, interval=1000 | schedule?)
Countdown value from startValue
down to 0
with indicated interval
in ms. Alternatively, a scheduler function can be passed as schedule
argument, that can be eg. worker-timers-based implementation.
const Demo = { const count reset = ; return `Remains: s`};
useValidate
[error, validate] = useValidate(validator: Function | Array, init? )
Provides validation functionality.
validator
is a function or an array of functionsvalue => error | true ?
.init
is optional initial value to validate.
{ let usernameError validateUsername = return <> <input onChange= && ...inputProps/> usernameError </>}
useFormField
[props, field] = useFormField( options )
Form field state controller. Handles input state and validation. Useful for organizing controlled inputs or forms, a nice minimal replacement to form hooks libraries.
let props field = // to set new input value return <input ...props />
options
value
- initial input value.persist = false
- persist input state between sessions.validate
- custom validator for input, modifiesfield.error
. SeeuseValidate
.required
- if value must not be empty....props
- the rest of props is passed toprops
field
value
- current input value.error
- current validation error. Revalidates on blur,null
on focus.valid: bool
- is valid value, revalidates on blur.focus: bool
- if input is focused.touched: bool
- if input was focused.set(value)
- set input value.reset()
- reset form state to initial.validate(value)
- force-validate input.
useInput
[value, setValue] = useInput( element | ref )
Uncontrolled input element hook. Updates if input value changes.
Setting null
/ undefined
removes attribute from element.
Useful for organizing simple input controllers, for advanced cases see useFormField.
{ let ref = let value setValue = return <input ref=ref />}
useObservable
[state, setState] = useObservable(observable)
Observable as hook. Plug in any spect/v, observable, mutant, observ be free.
const vCount = { let count setCount = return <>Count: count </>}
standard
For convenience, unihooks export current framework hooks. To switch hooks, use setHooks
- the default export.
{ let count setCount = }
utility
Utility hooks, useful for high-order-hooks.
update = useUpdate()
Force-update component, regardless of internal state.
prev = usePrevious(value)
Returns the previous state as described in the React hooks FAQ.
See also
License
MIT
HK