1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-18 09:35:20 +02:00
joplin/packages/lib/hooks/useNowEffect.ts
Henry Heino 4a88d6ff7a
Desktop: Multiple window support (#11181)
Co-authored-by: Laurent Cozic <laurent22@users.noreply.github.com>
2024-11-08 15:32:05 +00:00

29 lines
819 B
TypeScript

import type * as React from 'react';
import shim from '../shim';
type CleanupCallback = (()=> void)|null;
export type EffectFunction = ()=> CleanupCallback;
const { useRef, useMemo, useEffect } = shim.react();
// Like useEffect, but runs as soon as possible.
const useNowEffect = (effect: EffectFunction, dependencies: React.DependencyList) => {
const lastCleanup = useRef<CleanupCallback>(null);
const cleanupCallback = useMemo(() => {
lastCleanup.current?.();
lastCleanup.current = null;
return effect() ?? null;
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- This is a custom hook
}, dependencies);
lastCleanup.current = cleanupCallback;
useEffect(() => {
return () => {
lastCleanup.current?.();
lastCleanup.current = null;
};
}, []);
};
export default useNowEffect;