react#DependencyList TypeScript Examples
The following examples show how to use
react#DependencyList.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Change.effect.ts From ke with MIT License | 7 votes |
export function useChangeEffect(callback: EffectCallback, deps?: DependencyList): void {
const isFirstRun = useRef(true)
useEffect(() => {
if (isFirstRun.current) {
isFirstRun.current = false
return
}
callback()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
}
Example #2
Source File: useDidUpdateEffect.ts From parity-bridges-ui with GNU General Public License v3.0 | 6 votes |
/**
* Exactly like React's `useEffect`, but skips initial render. Tries to
* reproduce `componentDidUpdate` behavior.
*
* @see https://stackoverflow.com/questions/53179075/with-useeffect-how-can-i-skip-applying-an-effect-upon-the-initial-render/53180013#53180013
*/
export function useDidUpdateEffect(fn: EffectCallback, inputs?: DependencyList): void {
const didMountRef = useRef(false);
return useEffect(() => {
if (didMountRef.current) fn();
else didMountRef.current = true;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, inputs);
}
Example #3
Source File: useUpdateEffect.ts From lucide with ISC License | 6 votes |
useUpdateEffect = (effect: EffectCallback, deps?: DependencyList) => {
const isFirstRef = useRef(true);
if (isFirstRef.current) {
isFirstRef.current = false;
}
useEffect(() => {
if (!isFirstRef.current) {
return effect();
}
}, deps);
}
Example #4
Source File: useRefCallback.ts From anchor-web-app with Apache License 2.0 | 6 votes |
useRefCallback = <T extends (...args: any[]) => any>(
callback: T,
deps: DependencyList,
): T => {
const ref = useRef(callback);
useEffect(() => {
ref.current = callback;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return useMemo(
() =>
((...args) => {
const fn = ref.current;
return fn(...args);
}) as T,
[ref],
);
}
Example #5
Source File: useAsyncFn.ts From tailchat with GNU General Public License v3.0 | 6 votes |
export function useAsyncFn<T extends FunctionReturningPromise>(
fn: T,
deps: DependencyList = [],
initialState: StateFromFunctionReturningPromise<T> = { loading: false }
): AsyncFnReturn<T> {
const lastCallId = useRef(0);
const isMounted = useMountedState();
const [state, set] =
useState<StateFromFunctionReturningPromise<T>>(initialState);
const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
const callId = ++lastCallId.current;
set((prevState) => ({ ...prevState, loading: true }));
return fn(...args).then(
(value) => {
isMounted() &&
callId === lastCallId.current &&
set({ value, loading: false });
return value;
},
(error) => {
isMounted() &&
callId === lastCallId.current &&
set({ error, loading: false });
return error;
}
) as ReturnType<T>;
}, deps);
return [state, callback as unknown as T];
}
Example #6
Source File: index.ts From fe-v5 with Apache License 2.0 | 6 votes |
export default function useAsync<Result = any, Args extends any[] = any[]>(
fn: (...args: Args | []) => Promise<Result>,
deps: DependencyList = [],
) {
const [state, callback] = useAsyncFn<Result, Args>(fn, deps, {
loading: true,
});
useEffect(() => {
callback();
}, [callback]);
return state;
}
Example #7
Source File: hooks.tsx From kratos-selfservice-ui-react-nextjs with Apache License 2.0 | 6 votes |
// Returns a function which will log the user out
export function createLogoutHandler(deps?: DependencyList) {
const [logoutToken, setLogoutToken] = useState<string>('')
const router = useRouter()
useEffect(() => {
ory
.createSelfServiceLogoutFlowUrlForBrowsers()
.then(({ data }) => {
setLogoutToken(data.logout_token)
})
.catch((err: AxiosError) => {
switch (err.response?.status) {
case 401:
// do nothing, the user is not logged in
return
}
// Something else happened!
return Promise.reject(err)
})
}, deps)
return () => {
if (logoutToken) {
ory
.submitSelfServiceLogoutFlow(logoutToken)
.then(() => router.push('/login'))
.then(() => router.reload())
}
}
}
Example #8
Source File: hooks.tsx From ovineherd with Apache License 2.0 | 6 votes |
export function useSchema(option: UseSchemaOption, deps: DependencyList = []) {
const { schemaProps, schema: optSchema, apis: optApis, getSchema, getApis, filterSchema } = option
const { userInfo } = useAppContext()
const depArr = [userInfo].concat(deps)
const schemaComponent = useMemo(() => {
const schema = getSchema ? getSchema() : optSchema
const apis = getApis ? getApis() : optApis
set(schema, 'preset.apis', apis || {})
return (
<Amis
key={uuid()}
schema={filterSchema ? filterSchema(schema) : schema}
props={schemaProps}
/>
)
}, depArr)
return schemaComponent
}
Example #9
Source File: useAsync.ts From tailchat with GNU General Public License v3.0 | 6 votes |
// Reference: https://github.com/streamich/react-use/blob/master/src/useAsync.ts
export function useAsync<T extends FunctionReturningPromise>(
fn: T,
deps: DependencyList = []
) {
const [state, callback] = useAsyncFn(fn, deps, {
loading: true,
});
useEffect(() => {
callback();
}, [callback]);
return state;
}
Example #10
Source File: useDebounce.ts From phosphor-home with MIT License | 6 votes |
export default function useDebounce(
fn: Function,
ms: number = 0,
deps: DependencyList = []
): UseDebounceReturn {
const [isReady, cancel, reset] = useTimeoutFn(fn, ms);
useEffect(reset, deps);
return [isReady, cancel];
}
Example #11
Source File: useCustomCompareEffect.ts From web with MIT License | 6 votes |
/**
* Like `useEffect` but uses provided comparator function to validate dependency changes.
*
* @param callback Function that will be passed to underlying effect hook.
* @param deps Dependencies list, like for `useEffect` hook.
* @param comparator Function that compares two dependencies arrays, and returns true in case
* they're equal.
* @param effectHook Effect hook that will be used to run callback. Must comply `useEffect`
* signature, meaning that callback should be placed as first argument and dependencies list
* as second.
* @param effectHookRestArgs Extra arguments that passed to effectHook.
*/
export function useCustomCompareEffect<
Callback extends IEffectCallback = IEffectCallback,
Deps extends DependencyList = DependencyList,
HookRestArgs extends any[] = any[],
R extends HookRestArgs = HookRestArgs
>(
callback: Callback,
deps: Deps,
comparator: IDependenciesComparator<Deps> = basicDepsComparator,
effectHook: IEffectHook<Callback, Deps, HookRestArgs> = useEffect,
...effectHookRestArgs: R
): void {
const dependencies = useRef<Deps>();
// Effects not working in SSR environment therefore no sense to invoke comparator
if (
dependencies.current === undefined ||
(isBrowser && !comparator(dependencies.current, deps))
) {
dependencies.current = deps;
}
effectHook(callback, dependencies.current, ...effectHookRestArgs);
}
Example #12
Source File: useDebounce.ts From iconsax-react with MIT License | 6 votes |
export function useDebounce(
fn: Function,
ms: number = 0,
deps: DependencyList = []
): UseDebounceReturn {
const [isReady, cancel, reset] = useTimeoutFn(fn, ms);
useEffect(reset, deps);
return [isReady, cancel];
}
Example #13
Source File: useAsyncEffect.ts From save-food with MIT License | 6 votes |
useAsyncEffect = (
asyncFunction: () => Promise<void | (() => void)>,
deps?: DependencyList,
) => {
useEffect(() => {
let shouldClear = false
let clearCallback: void | (() => void)
const maybeClear = () => {
if (clearCallback && shouldClear) {
clearCallback()
}
}
Promise.resolve(asyncFunction())
.then((clear) => {
clearCallback = clear
maybeClear()
})
.catch((error: any) => {
console.error('useAsyncEffect', error)
})
return () => {
shouldClear = true
maybeClear()
}
}, deps)
}
Example #14
Source File: react-helpers.ts From project-loved-web with MIT License | 6 votes |
export function useEffectExceptOnMount(effect: EffectCallback, deps?: DependencyList): void {
const firstUpdate = useRef(true);
useEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
return effect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
Example #15
Source File: index.ts From react-panorama with MIT License | 6 votes |
/**
* Executes `callback` every time `eventName` game event is fired.
*/
export function useGameEvent<T extends string | object>(
eventName:
| (T extends string ? T : string)
| keyof CustomGameEventDeclarations
| keyof GameEventDeclarations,
callback: (event: NetworkedData<GameEvents.InferGameEventType<T, object>>) => void,
dependencies?: DependencyList,
) {
useEffect(() => {
const id = GameEvents.Subscribe(eventName, callback);
return () => GameEvents.Unsubscribe(id);
}, dependencies);
}
Example #16
Source File: progress.tsx From backstage with Apache License 2.0 | 6 votes |
/**
* Similar to useAsync except it "waits" for a dependent (upstream) async state
* to finish first, otherwise it forwards the dependent pending state.
*
* When/if the dependent state has settled successfully, the callback will be
* invoked for a new layer of async state with the dependent (upstream) success
* result as argument.
*/
export function useAsyncChain<S extends ProgressType<any> | AsyncState<any>, R>(
parentState: S,
fn: (value: NonNullable<S['value']>) => Promise<R>,
deps: DependencyList,
): Unsuccessful<S> | AsyncState<R> {
const childState = useAsync(
async () => (!parentState.value ? sentry : fn(parentState.value)),
[!parentState.error, !parentState.loading, parentState.value, ...deps],
);
if (!parentState.value) {
return parentState as Unsuccessful<S>;
} else if (childState.value === sentry) {
return { loading: true };
}
return childState as AsyncState<R>;
}
Example #17
Source File: hookUtils.ts From airmessage-web with Apache License 2.0 | 6 votes |
/**
* Wrapper for useEffect, that passes a function that can wrap a promise
* whose result will be ignored if it resolves after the component unmounts
*/
export function useCancellableEffect(
effect: (
addPromise: <T>(promise: Promise<T>) => Promise<T>
) => void | VoidFunction,
deps?: DependencyList
) {
useEffect(() => {
let isCancelled = false;
const cleanup = effect(<T>(promise: Promise<T>): Promise<T> => {
return new Promise<T>((resolve, reject) => {
promise
.then((val) => !isCancelled && resolve(val))
.catch((error) => !isCancelled && reject(error));
});
});
return () => {
isCancelled = true;
cleanup?.();
};
}, deps); //eslint-disable-line react-hooks/exhaustive-deps
}
Example #18
Source File: Pre.effect.ts From ke with MIT License | 6 votes |
export function usePreEffect(callback: EffectCallback, deps?: DependencyList): boolean {
const hasFirstRun = useRef(false)
useEffect(() => {
hasFirstRun.current = true
callback()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
return hasFirstRun.current
}
Example #19
Source File: ObjectHookHelper.ts From react-native-design-kit with MIT License | 6 votes |
export function useDidUpdate(
effect: React.EffectCallback,
deps?: DependencyList,
) {
const initialize = useRef(false);
useEffect(() => {
if (initialize.current) {
return effect();
} else {
initialize.current = true;
}
}, deps);
}
Example #20
Source File: useAddEventsCallback.ts From ke with MIT License | 6 votes |
/**
* TODO: сделать что-то, чтобы при изменении deps переприменялись обработчики событий
* Основная проблема, что их довольно сложно удалять из eventManager. Возможно,
* в таких ситуациях нужно просто целиком пересоздавать его, если это допустимо
* в рамках API яндекса.
*/
export function useAddEventsCallback(
callback: (control: never) => void,
deps: DependencyList
): (control: never | null) => void {
const eventsHasAddedRef = useRef(false)
return useCallback((control: never | null) => {
if (!control || eventsHasAddedRef.current) {
return
}
callback(control)
eventsHasAddedRef.current = true
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
}
Example #21
Source File: useDebounce.ts From sc-translator-crx with GNU General Public License v3.0 | 6 votes |
useDebounce = (fn: () => void, ms: number, deps: DependencyList) => {
const timerRef = useRef<ReturnType<typeof setTimeout>>();
const debounceRef = useRef<() => void>();
const callbackRef = useRef(fn);
useEffect(() => {
callbackRef.current = fn;
}, [fn]);
useEffect(() => {
debounceRef.current = () => {
timerRef.current && clearTimeout(timerRef.current);
timerRef.current = setTimeout(callbackRef.current, ms);
};
return () => {
timerRef.current && clearTimeout(timerRef.current)
};
}, [ms]);
useEffect(() => {
debounceRef.current?.();
// eslint-disable-next-line
}, deps);
}
Example #22
Source File: useGameEvent.ts From r3f-game-demo with MIT License | 6 votes |
export default function useGameEvent<T extends PubSubEvent>(
eventName: T['name'],
callback: (data: T['data']) => void,
deps: DependencyList = []
) {
const callbackRef = useRef<typeof callback>();
const { subscribe } = useGame();
callbackRef.current = callback;
useEffect(() => {
return subscribe(eventName, callbackRef.current);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [subscribe, eventName, ...deps]);
}
Example #23
Source File: useSubscription.ts From apps with GNU Affero General Public License v3.0 | 6 votes |
export default function useSubscription<T>(
request: () => { query: string; variables?: Record<string, unknown> },
{ next, error }: SubscriptionCallbacks<T>,
deps?: DependencyList,
): void {
const { subscriptionClient, connected } = useContext(SubscriptionContext);
const nextRef = useRef(next);
const errorRef = useRef(error);
useEffect(() => {
nextRef.current = next;
}, [next]);
useEffect(() => {
errorRef.current = error;
}, [error]);
useEffect(() => {
if (connected) {
return subscriptionClient.subscribe<T>(request(), {
next: ({ data }: Payload<T>) => {
nextRef.current?.(data);
},
error: (subscribeError) => errorRef.current?.(subscribeError),
complete: () => {},
});
}
return undefined;
}, [connected, ...(deps ?? [])]);
}
Example #24
Source File: useDebounceEffect.ts From ace with GNU Affero General Public License v3.0 | 6 votes |
useChangeDebounce = (fn: Function, ms?: number, deps?: DependencyList) => {
const lastDepValues = useRef(deps);
useDebounce(() => {
if (lastDepValues.current.some((it, index) => it !== deps[index])) {
fn();
}
lastDepValues.current = deps;
}, 500, [deps, fn]);
}
Example #25
Source File: useAsync.ts From gio-design with Apache License 2.0 | 6 votes |
function useAsyncFn<T extends FunctionReturningPromise>(
fn: T,
deps: DependencyList = [],
initialState: StateFromFunctionReturningPromise<T> = { loading: false }
): AsyncFnReturn<T> {
const lastCallId = useRef(0);
const isMounted = useMountedState();
const [state, set] = useState<StateFromFunctionReturningPromise<T>>(initialState);
const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
// eslint-disable-next-line no-plusplus
const callId = ++lastCallId.current;
set((prevState) => ({ ...prevState, loading: true }));
return fn(...args).then(
(value) => {
isMounted() && callId === lastCallId.current && set({ value, loading: false });
return value;
},
(error) => {
isMounted() && callId === lastCallId.current && set({ error, loading: false });
return error;
}
) as ReturnType<T>;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return [state, callback as unknown as T];
}
Example #26
Source File: useThrottleEffect.ts From use-antd-resizable-header with MIT License | 6 votes |
function useThrottleEffect(effect: EffectCallback, deps?: DependencyList, options?: Options) {
const [flag, setFlag] = useState({});
const { run, cancel } = useThrottleFn(() => {
setFlag({});
}, options);
useEffect(() => {
return run();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
// eslint-disable-next-line react-hooks/exhaustive-deps
React.useEffect(cancel, []);
useUpdateEffect(effect, [flag]);
}
Example #27
Source File: useEventListener.ts From posthog-foss with MIT License | 6 votes |
export function useEventListener(
eventName: string,
handler: EventHandler | KeyboardEventHandler,
element: Element | Window = window,
deps?: DependencyList
): void {
// Create a ref that stores handler
const savedHandler = useRef<EventHandler>(() => {})
// This allows our effect below to always get latest handler without us needing to pass it in effect deps array,
// which would potentially cause effect to re-run every render
useEffect(() => {
savedHandler.current = handler as EventHandler
}, [handler])
useEffect(
() => {
// Make sure element supports addEventListener
if (!element?.addEventListener) {
console.warn(
`Could not start listening to ${eventName} on ${(element as Element)?.localName ?? 'window'}!`
)
return
}
// Create event listener that calls handler function stored in ref
const eventListener: EventHandler = (event) => savedHandler.current(event)
// Add event listener
element.addEventListener(eventName, eventListener)
// Remove event listener on cleanup
return () => {
element?.removeEventListener(eventName, eventListener)
}
},
[eventName, element, ...(deps || [])] // Re-run if eventName or element changes
)
}
Example #28
Source File: useUpdateEffect.ts From usehooks-ts with MIT License | 6 votes |
function useUpdateEffect(effect: EffectCallback, deps?: DependencyList) {
const isFirst = useIsFirstRender()
useEffect(() => {
if (!isFirst) {
return effect()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
}
Example #29
Source File: useSSE.tsx From useSSE with MIT License | 5 votes |
/**
*
* @param effect runction returning promise
* @param dependencies list of dependencies like in useEffect
*/
export function useSSE<T>(
effect: () => Promise<any>,
dependencies?: DependencyList
): T[] {
const internalContext: IInternalContext = useContext(InternalContext);
let callId = internalContext.current;
internalContext.current++;
const ctx: IDataContext = useContext(DataContext);
const [data, setData] = useState(ctx[callId]?.data || null);
const [error, setError] = useState(ctx[callId]?.error || null);
if (!internalContext.resolved) {
let cancel = Function.prototype;
const effectPr = new Promise((resolve) => {
cancel = () => {
if (!ctx[callId]) {
ctx[callId] = { error: { messgae: "timeout" }, id: callId };
}
resolve(callId);
};
return effect()
.then((res) => {
return res;
})
.then((res) => {
ctx[callId] = { data: res };
resolve(callId);
})
.catch((error) => {
ctx[callId] = { error: error };
resolve(callId);
});
});
internalContext.requests.push({
id: callId,
promise: effectPr,
cancel: cancel,
});
}
useEffect(() => {
if (internalContext.resolved && !ctx[callId]) {
effect()
.then((res) => {
setData(res);
})
.catch((error) => {
setError(error);
});
}
delete ctx[callId];
}, dependencies);
return [data, error];
}