Skip to content

Comments

hooks / useDebounce#76

Open
VaseninaNastya wants to merge 35 commits intomasterfrom
feature/useDebounce
Open

hooks / useDebounce#76
VaseninaNastya wants to merge 35 commits intomasterfrom
feature/useDebounce

Conversation

@VaseninaNastya
Copy link

No description provided.

@VaseninaNastya VaseninaNastya changed the title feat: add useDebounce hooks / useDebounce Feb 18, 2024
@sadcitizen
Copy link
Member

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

@SmorodinVik SmorodinVik requested a review from Oustinger December 5, 2024 14:50
@AMZhukov
Copy link
Contributor

AMZhukov commented Dec 11, 2024

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

Результат применения хука 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
Member

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

@sadcitizen
Copy link
Member

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

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

Choose a reason for hiding this comment

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

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

Copy link
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
Member

Choose a reason for hiding this comment

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

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

Copy link
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
Member

Choose a reason for hiding this comment

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

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

Copy link
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