Skip to content

Commit

Permalink
fix(useLayoutEffectCall): rm useState (#7964)
Browse files Browse the repository at this point in the history
  • Loading branch information
SevereCloud authored Nov 20, 2024
1 parent e1077e5 commit 9ada42b
Showing 1 changed file with 7 additions and 29 deletions.
36 changes: 7 additions & 29 deletions packages/vkui/src/components/View/useLayoutEffectCall.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,20 @@
import * as React from 'react';
import { useIsomorphicLayoutEffect } from '../../lib/useIsomorphicLayoutEffect';

class LayoutEffectCall {
#fns: Array<() => void> = [];

/**
* Выполняет переданные функции
*/
run() {
for (const fn of this.#fns) {
fn();
}

this.#fns = [];
}

/**
* Вызовет функцию после изменения DOM, но до того как пользователь увидит
* изменения
*/
add = (fn: () => void) => {
this.#fns.push(fn);
};
}

/**
* Возвращает функцию которая вызывает callback после изменения DOM, но до того
* как пользователь увидит изменения
*/
export function useLayoutEffectCall() {
const ref = React.useRef<LayoutEffectCall | null>(null);
if (!ref.current) {
ref.current = new LayoutEffectCall();
}
const [fns] = React.useState<Array<() => void>>(() => []);

useIsomorphicLayoutEffect(() => {
ref.current!.run();
while (fns.length > 0) {
fns.pop()!();
}
});

return ref.current.add;
const add = React.useCallback((fn: () => void) => fns.push(fn), [fns]);

return add;
}

0 comments on commit 9ada42b

Please sign in to comment.