'Why is there a delay when I do useState and useEffect to update a variable?

I saw quite a few posts about a delay between setting the state for a component, however, I'm running into this issue in a custom hook that I built. Basically, the classNames that I'm returning are being applied, just with a delay after the component first renders. I've tried using callback functions and useEffect with no luck. Does anyone have any ideas about why there is a small delay?

import * as React from 'react';
import classNames from 'classnames';
import debounce from 'lodash/debounce';

const useScrollStyling = ref => {
    const [isScrolledToBottom, setIsScrolledToBottom] = React.useState(false);
    const [isScrolledToTop, setIsScrolledToTop] = React.useState(true);
    const [isOverflowScrollingEnabled, setIsOverflowScrollingEnabled] = React.useState(false);
    const { current } = ref;

    React.useEffect(() => {
        if (current) {
            const { clientHeight, scrollHeight } = current;
            setIsOverflowScrollingEnabled(scrollHeight > clientHeight);
        }
    }, [current]);

    const handleScroll = ({ target }) => {
        const { scrollHeight, scrollTop, clientHeight } = target;
        const isScrolledBottom = scrollHeight - Math.ceil(scrollTop) === clientHeight;
        const isScrolledTop = scrollTop === 0;
        setIsScrolledToBottom(isScrolledBottom);
        setIsScrolledToTop(isScrolledTop);
    };

    return {
        handleScroll: React.useMemo(() => debounce(handleScroll, 100), []),
        scrollShadowClasses: classNames({
            'is-scrolled-top': isOverflowScrollingEnabled && isScrolledToTop,
            'is-scrolled-bottom': isScrolledToBottom,
            'is-scrolled': !isScrolledToTop && !isScrolledToBottom,
        }),
    };
};

export default useScrollStyling;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source