- useInlineEffect - Calls an effect immediately.
- useLazyRef - Ref with a function initializer.master
parent
8c042e7bed
commit
e68ed8b481
12
src/Main.ts
12
src/Main.ts
|
@ -4,9 +4,18 @@ export { default as useAsyncEffect } from './useAsyncEffect';
|
|||
export type { AsyncMemoOptions, AsyncMemoFunction } from './useAsyncMemo';
|
||||
export { default as useAsyncMemo } from './useAsyncMemo';
|
||||
|
||||
export type { InlineEffectFunction } from './useInlineEffect';
|
||||
export { default as useInlineEffect } from './useInlineEffect';
|
||||
|
||||
export { default as useLazyRef } from './useLazyRef';
|
||||
|
||||
export { default as useMediaMatches } from './useMediaMatches';
|
||||
|
||||
export type { MessagingCallback, MessagingCallbacks, MessagingOptions } from './useMessaging';
|
||||
export type {
|
||||
MessagingCallback,
|
||||
MessagingCallbacks,
|
||||
MessagingOptions,
|
||||
} from './useMessaging';
|
||||
export { default as useMessaging } from './useMessaging';
|
||||
|
||||
export { default as usePrevious } from './usePrevious';
|
||||
|
@ -14,3 +23,4 @@ export { default as usePrevious } from './usePrevious';
|
|||
export { default as useRerender } from './useRerender';
|
||||
|
||||
export { default as useStoredState } from './useStoredState';
|
||||
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
import { useRef } from 'react';
|
||||
|
||||
/** A hook's dependants, either an array of unknown values or undefined. */
|
||||
export type Dependants = unknown[];
|
||||
|
||||
/** A function supplied to `useInlineEffect`. */
|
||||
export type InlineEffectFunction = () => void;
|
||||
|
||||
/**
|
||||
* Executes an effect function *immediately*, without waiting for the Component render to end.
|
||||
* Dependents can be supplied to prevent the effect from re-executing, same as with `useEffect`.
|
||||
*
|
||||
* @param fn - The function to call.
|
||||
* @param dep - An optional array of dependants, following the functionality of `useEffect`.
|
||||
*/
|
||||
|
||||
export default function useInlineEffect(fn: InlineEffectFunction, dep?: Dependants) {
|
||||
const previous = useRef<undefined | unknown[]>(undefined);
|
||||
|
||||
let isDirty = !previous.current || !dep || dep.length !== previous.current.length;
|
||||
if (!isDirty && dep && previous.current) {
|
||||
for (let i = 0; i < dep.length; i++) {
|
||||
if (dep[i] !== previous.current[i]) {
|
||||
isDirty = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isDirty) fn();
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
import { useState, MutableRefObject } from 'react';
|
||||
|
||||
/**
|
||||
* Creates a Ref, using a function initializer.
|
||||
*
|
||||
* @param value - A function that returns the ref's initial value.
|
||||
* @returns a ref.
|
||||
*/
|
||||
|
||||
export default function useLazyRef<T = any>(initializer: () => T): MutableRefObject<T> {
|
||||
const [ref] = useState(() => ({ current: initializer() }));
|
||||
return ref;
|
||||
}
|
Loading…
Reference in New Issue