-
Notifications
You must be signed in to change notification settings - Fork 184
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(useLayoutEffectCall): rm useState (#7964)
- Loading branch information
1 parent
e1077e5
commit 9ada42b
Showing
1 changed file
with
7 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |