Skip to content

hooks / useDebounce#76

Open
VaseninaNastya wants to merge 36 commits into
masterfrom
feature/useDebounce
Open

hooks / useDebounce#76
VaseninaNastya wants to merge 36 commits into
masterfrom
feature/useDebounce

Conversation

@VaseninaNastya

Copy link
Copy Markdown

No description provided.

@VaseninaNastya VaseninaNastya changed the title feat: add useDebounce hooks / useDebounce Feb 18, 2024
Comment thread hooks/use-window-size/package.json
Comment thread hooks/use-debounce/src/useDebounce.ts Outdated
Comment thread hooks/use-debounce-callback/package.json Outdated
Comment thread hooks/use-debounce/src/useDebounce.stories.mdx
@sadcitizen

Copy link
Copy Markdown
Member

@SmorodinVik докати этот PR, пожалуйста

Comment thread hooks/use-debounced-callback/src/useDebouncedCallback.stories.tsx Outdated
Comment thread hooks/use-debounced-callback/src/useDebouncedCallback.tests.tsx
Comment thread hooks/use-debounced-value/README.md
Comment thread hooks/use-debounced-value/src/useDebouncedValue.tests.tsx Outdated
Comment thread hooks/use-debounced-callback/package.json
@SmorodinVik SmorodinVik requested a review from Oustinger December 5, 2024 14:50
@AMZhukov

AMZhukov commented Dec 11, 2024

Copy link
Copy Markdown
Contributor

В продолжении разговора на созвоне.

Результат применения хука useTimeout:

import useTimeout from '@byndyusoft-ui/use-timeout';
import { useCallback, useRef, useState } from 'react';

export function useDebouncedCallback<A extends any[]>(
    callback: (...args: A) => void,
    delay: number
): (...args: A) => void {
    const [args, setArgs] = useState<A>();
    const [shouldExecute, setShouldExecute] = useState(false);

    useTimeout(() => {
        if (shouldExecute) {
            callback(...args!);
            setShouldExecute(false)
        }
    }, shouldExecute ? delay : null);

    return useCallback((...newArgs: A) => {
        setShouldExecute(true);
        setArgs(newArgs);
    }, []);
}
export default useDebouncedCallback

@sadcitizen

Copy link
Copy Markdown
Member

Заблокировано реализацией useTimeout

@sadcitizen

Copy link
Copy Markdown
Member

@sadcitizen посмотрит и зарелизит в новогодние праздники

<hr />
<div className="container">
<div className="row">
<div className="use-array__container">

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем это надо было делать?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

При запуске сторибуки классы с одинаковыми именами из других историй влияли друг на друга, добавлял это как временное решение. Сейчас поменял на css модули.


type THookReturn<T> = [T, (arg: T) => void];

export default function useDebouncedValue<T>(value: T, delay = 300): THookReturn<T> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Начальное значение хука может быть задано не только значением, но и функцией. В пакете с типами был тип InitialState

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поправил


const cleanup = () => clearTimeout(timeoutIdRef.current);

useEffect(() => cleanup(), []);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А в блоке return точно не надо вызывать очистку? Что будет, если компонент, который вызывает хук, будет размонтирован до того как коллбек выполнится? Этот вызов надо бы отменить, иначе могут быть утечки памяти.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Применил хук useTimeout, в нём очистка производится при размонтировании хука. Также дописал тест на это дело. Тест называется cleans up timer on unmount

@AMZhukov AMZhukov force-pushed the feature/useDebounce branch from dcf3a22 to f0665de Compare January 8, 2025 13:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants