any-fish
v2.1.0
Published
Utility React Hooks for any purpose
Downloads
58
Maintainers
Readme
AnyFish
Utility React Hooks for any purpose. There is a Hook for Any Fish.
Installation
yarn add any-fish
npm install any-fish
TypeScript usage
The package is written in TypeScript, so no additional @types packages are needed.
useBoolean
Call signature
(initialState) => [boolean, SwitchToTrue, SwitchToFalse, Toggle, Dispatch<SetStateAction<boolean>>]
Description
A convenience wrapper for useState to manage boolean flags.
Arguments
- initialState (optional):
boolean | (() => boolean)
- same as you'd pass touseState<boolean>
. Defaults tofalse
.
Type aliases
SwitchToTrue, SwitchToFalse, Toggle are all just plain void functions (() => void
). SwitchToTrue sets
the flag value to true
, SwitchToFalse sets it to false
, and Toggle sets it to be the opposite of the current
value.
useDelayedValue
Call signature
(initialState, options) => [State, DebouncedFunc<SetState>, SetState]
Description
A convenience wrapper for useState that lets you debounce or throttle value updates.
Arguments
- initialState:
T | (() => T)
- same as you'd pass touseState
. - options (optional):
Partial<Options>
- adjustments for delay logic.
Type aliases
- Options:
{ delay: number, delayFn: 'debounce' | 'throttle', }
delay
defines the throttle / debounce timeout. Defaults to 300.delayFn
defines how to delay the setter. Defaults todebounce
.
Returned value
Returned value is a tuple:
- The current state value
- The delayed state setter
- The original state setter (executes immediately, not wrapped in neither
debounce
northrottle
)
useDidMount
Call signature
(effect) => void
Description
Executes the effect after the initial render.
Arguments
- effect:
() => void
- The effect to execute. The return value is ignored. Use plain useEffect for effects that need cleanup.
useDimensions
Call signatures
(src, mediaKind) => Dimensions | null
: Calculates the dimensions of a visual media object by its source.- src:
string
- The media object source, same as the one passed to<img />
or<video />
. - mediaKind (optional):
useDimensions.MediaKind
- Defines whether a Video or an Image is measured. Defaults toMediaKind.Image
.
- src:
(options) => [Dimensions | null, RefCallback]
: Returns a callback ref to pass to a DOM element and calculates the dimensions of that element.- options (optional):
Partial<Options>
- Adjustments for measuring behaviour.
- options (optional):
Type aliases
- Dimensions:
{ width: number, height: number }
- Options:
Pass{ originalRef: MutableRefObject | RefCallback, throttle: number, }
originalRef
if you need to use some extra ref logic alongside the one provided by the hook.throttle
can serve for optimization purposes if the measured element's size changes too often. - MutableRefObject: Return type of useRef.
- RefCallback
useEventListener
Call signatures
(targetPointer, eventName, options, ...eventListeners) => void
(targetPointer, eventName, eventListener, options) => void
(targetPointer, eventName, ...eventListeners) => void
(eventName, options, ...eventListeners) => void
(eventName, eventListener, options) => void
(eventName, ...eventListeners) => void
Description
Adds the provided listeners to the target and performs automatic cleanup. Call signatures № 4, 5 & 6 are shorthands for
adding listeners to window
.
Arguments
- targetPointer:
Target
- Points to the element which events are to be handled. - eventName:
string
- The name of the event to handle. - eventListener:
Listener
- The handler for the event. - options:
Options
- The options to pass toaddEventListener
.
Type aliases
- Target:
EventTarget | RefObject
- anything that supportsaddEventListener
andremoveEventListener
, or a React Ref holding a reference to one. - For types of Listener and Options, see the corresponding MDN page.
useIsMounted
Call signature
() => (() => boolean)
Description
Returns a function to access the mounted state of a functional component.
useMediaQuery
Call signatures
(mediaQuerySource, options) => boolean
- Checks if window matches provided media query- mediaQuerySource:
string
- The media query to match against. - options (optional):
Partial<Options>
- Adjustments for matching behaviour
- mediaQuerySource:
<K>(mediaQuerySources, options) => Record<K, boolean>
- mediaQuerySource:
Record<K, string>
- The media queries to match against. - options (optional):
Partial<Options>
- Adjustments for matching behaviour
- mediaQuerySource:
Type aliases
- Options:
With{ track: boolean, throttle: number, }
track
set tofalse
the window will only be matched against the provided query once, otherwise the matching result will be tracked. Defaults totrue
.throttle
defines the throttle timeout when tracking the matching result. Defaults to 300.
useMountedState
Call signature
(initialState) => [State, SetState]
Description
A combination of plain useState
and useIsMounted. Useful for async operations like data fetching, when setState
can potentially be
called after the component has already unmounted, to avoid the "Cannot set state on an unmounted component" warnings and
leaks.
The call signature is identical to useState.
usePersistentState
Call signature
(initialState, key, options) => [State, SetState]
Description
A convenience wrapper for useState that lets you keep data in a persistent browser storage (i. e. localStorage).
Arguments
- key:
string
- The key to store the data at. - options (optional):
Partial<Options>
- Adjustments for storing behaviour.
Type aliases
- Options:
{ storage: Storage, serializer: { stringify: (value: State) => string, parse: (serialized: string) => State }, cleanup: boolean, follow: boolean, clearOnParsingError: boolean, }
storage
is either localStorage, sessionStorage or any custom construction implementing the same interface. By default, localStorage is used.serializer
allows for customizing the way the data is serialized and deserialized. By default, this is done via JSON.cleanup
defines whether the stored value should be cleaned up wheneveroptions.storage
,options.serializer
orkey
change. Defaults totrue
.follow
defines whether wheneveroptions.storage
,options.serializer
orkey
change, the state value should be updated to whatever is stored at that "new address". Defaults tofalse
.clearOnParsingError
defines whether the stored data should be cleared if theserializer
fails to parse it. Defaults totrue
.
Returned value
Returned value is identical to useState.
usePrevious
Call signature
(value, initialValue) => previousValue
Description
Returns the previous value of a variable.
Arguments
- value:
T
- Current value. - initialValue (optional):
T
- Initial value. Defaults tovalue
.
usePromise
Call signatures
(promiseCreator, options) => HookResult
(promiseCreator, deps, options) => HookResult
Description
Tracks the lifecycle of a Promise, handles data storing and error catching. If deps
are provided, automatically calls
the async function on their update.
Arguments
- promiseCreator:
(...args: Deps) => Promise<Data>
- The async function to create the tracked Promise. - deps (optional):
Deps
- The array of dependencies that should trigger thepromiseCreator
. - options (optional):
Partial<Options>
- Customize the way the data is operated.
Type aliases
- Options:
{ resolveRace: usePromise.ResolveRace, onStart: () => void, onSuccess: (result) => void, onError: (e) => void, onAny: () => void, skip: boolean | ((...deps) => boolean), triggerOnSameDeps: boolean, }
resolveRace
defines how the hook should behave if a new Promise is launched while some other one is already running.ResolveRace.TakeFirst
waits for the first launched Promise to finish before accepting any new triggers,ResolveRace.TakeLast
(default) drops any running process whenever a new one is launched.onStart
is executed before any operation.onSuccess
is executed whenever the Promise resolves; the resolved value is passed as an argument.onError
is executed whenever the Promise rejects; the rejection reason is passed as an argument.onAny
is executed in thefinal
block.skip
is either a flag or a function returning one, defining whether the automatic trigger should be skipped for the current set of dependencies. By default, each dependency in the array is checked to neither benull
norundefined
.triggerOnSameDeps
forces the hook to trigger the promise creator on shallowdeps
change even if current deps are deep equal to the previous ones.
Returned value
The returned value is an array, with the following values at each position:
- The resolved data (or
undefined
, if no Promise has resolved yet). - The error (or whatever other value the Promise rejects with).
- A flag representing the "processing" state of the Promise.
- An object holding the following properties:
status
- the precise representation of the current state of the Promise. Can bePending
,Processing
,Resolved
orRejected
.trigger
- a function allowing for manual launching of a new Promise. Accepts the same arguments as the originalpromiseCreator
.
useReRenderTrigger
Call signature
() => (() => void)
Description
Returns a function that forces the Component to re-render when called.
useRenderCount
Call signature
() => (() => number)
Description
The hook is mostly meant for debugging purposes. Returns a function to access the amount of times the Component has rendered.
useSelectiveEffect
Call signature
(effect, deps, options) => void
Description
A convenience wrapper for useEffect that only triggers
the effect
when deps
deeply change.
Arguments
- effect:
() => (void | (() => void))
- The effect to execute. - deps:
unknown[]
- The dependencies array. - options (optional):
Partial<Options>
- Adjustments for execution behaviour.
Type aliases
- Options:
{ compare: (prev: Deps, curr: Deps) => boolean }
compare
defines how the change indeps
is detected. By default, Lodash.isEqual is used.
useSnapshotState
Call signature
(initialValue, externalControls, isValueValid) => [State, SetState]
Description
Example: a component accepts an onChange
prop of type (newValue: number) => void
, but needs to perform updates
based on the previous value (i.e., on increment you'd probably do onChange(value + 1)
). However, with such approach
it's impossible to persist the increment
function's reference equality: it would need to be re-created on each value
update. useSnapshotState
solves this problem: it accepts an external setValue
that only works with plain values, and
returns a persistent SetState
callback that works with reducer-like updates, just like the setter returned
by useState
. Also, in case external setter or value aren't provided (the component is uncontrolled), the hook would
manage the state internally.
Example
type Props = { onPageChange?: (page: number) => void, page?: number };
const Pagination: FC<Props> = props => {
const [page, setPage] = useSnapshotState(1, { value: props.page, setValue: props.onPageChange });
// setPage does not depend on current page, so these callbacks keep reference equality
const decrement = useCallback(() => setPage(curr => curr - 1), [setPage]);
const increment = useCallback(() => setPage(curr => curr + 1), [setPage]);
// page is reactive, so it can be used in jsx rendering
return (
<>
<button onClick={decrement}>-</button>
<span>{page}</span>
<button onClick={increment}>+</button>
</>
);
};
const fetchPageData = (page: number) => {
// I.e., some API stuff here
};
const MyPage: FC = () => (
<Pagination onPageChange={fetchPageData} />
)
Arguments
- initialValue:
T | (() => T)
- The initial value, like for useState. - externalControls (optional):
Partial<{ value: T, setValue: (newValue: T) => void }>
- External handlers to make the component controlled. - isValueValid (optional):
(v: T | undefined) => v is T
- a type guard to check that the providedexternalControls.value
fits and should be used as the returned reactive value. Defaults tov => v !== undefined
.
Returned value
The returned value is identical to useState.
useUpdate
Call signature
(effect, deps, options) => ((overrideOptions) => void)
Description
A convenience wrapper for useEffect when the first N deps
updates should not trigger the effect.
Arguments
- effect:
() => (void | (() => void))
- The effect to execute. - deps:
unknown[]
- The dependencies array. - options (optional):
Partial<Options>
- Adjustments for execution behaviour.
Type aliases
- Options:
{ nthUpdate: number, withCleanup: boolean, once: boolean, isInStrictMode: boolean, }
nthUpdate
defines which change ofdeps
should first trigger theeffect
. The count is 0-based: render №0 is the initial render. Defaults to1
, meaning the initial render is skipped.withCleanup
defines whether the cleanup function returned by theeffect
should be taken in account. Defaults totrue
.
Ifonce
is set totrue
, the effect and its cleanup will only be executed once after the Nth update. Defaults tofalse
.isInStrictMode
defines whether the hook is used within StrictMode; unfortunately, this can't be detected automatically, while it is essential when calculating which render should trigger the effect. Defaults totrue
.
Returned value
Returned value is a function allowing you to reset the counter and, if you need to, update the used options for the next cycle.
useWillUnmount
Call signature
(effect) => void
Description
Executes the effect before the component unmounts.
Arguments
- effect:
() => void
- The effect to execute.
Package settings
The package exposes a Settings
object. You can modify it to refine some global behaviour. The following settings are
available:
- isDev:
(() => boolean) | boolean
- Either a flag or a function returning one, defining whether the app is running in development environment. By default, the app is considered to be in development ifprocess.env.NODE_ENV
isdevelopment
. - allowConsole:
((method) => boolean) | boolean
- Either a flag or a function returning one, defining whether the package is allowed to write to console.method
is the name of console logging method used (log
,error
,warn
etc.). By default, the logs are turned on ifisDev
istrue
. - defaults - a complex field containing fallback options and settings for hooks:
- delay:
number
- The fallback delay to use for debouncing and throttling. Defaults to 300. - isEqual:
(a, b) => boolean
- The fallback comparison function. Defaults to Lodash.isEqual. - options - a complex field containing fallback options for hooks:
- delayedValue - fallback options for useDelayedValue.
delay
might be omitted, in such caseSettings.defaults.delay
will be used. Defaults to{ delayFn: 'debounce' }
. - mediaQuery - fallback options for useMediaQuery.
throttle
might be omitted, in such caseSettings.defaults.delay
will be used. Defaults to{ track: true }
. - persistentState - fallback options for usePersistentState.
storage
might be omitted (should be, if your app does not only run in browser environment). Defaults to{ serializer: { stringify: value => JSON.stringify({ value }), parse: serialized => JSON.parse(serialized).value, }, cleanup: true, follow: false, clearOnParsingError: true, }
- update - fallback options for useUpdate. Defaults to
{ nthUpdate: 1, withCleanup: true, once: false, isInStrictMode: true, }
- delayedValue - fallback options for useDelayedValue.
- delay: