Skip to main content

useSticky

React Hook that tracks element sticky

Usage

Live Editor
function Demo() {
  const element = useRef<HTMLDivElement>(null);
  const [isSticky] = useSticky(element, {
    // header fixed height
    nav: 64,
  });

  const stickyStyle: CSSProperties = isSticky
    ? {
        position: "fixed",
        top: 64,
        zIndex: 50,
        height: 20,
      }
    : {
        height: 20,
      };

  const guardStyle: CSSProperties = {
    width: 1,
    height: 1,
  };

  return (
    <div style={{height: 300,overflow: 'scroll'}}>
      <div ref={element} style={guardStyle} />
      <button style={stickyStyle}>
        {isSticky ? "stickying" : "not sticky"}
      </button>
      <div style={{ height: "100vh" }} />
    </div>
  );
};

Result
Loading...

API

useSticky

Returns

[boolean, React.Dispatch<React.SetStateAction<boolean>>]: A tuple with the following elements:

  • The current state of sticky.
  • A function to update the value of sticky.

Arguments

ArgumentDescriptionTypeDefaultValue
targetElementdom elementBasicTarget<HTMLElement> (Required)-
paramsoptional paramsUseStickyParams (Required)-
scrollElementscroll containerBasicTarget<HTMLElement>-

UseStickyParams

PropertyDescriptionTypeDefaultValue
axisaxis of scroll'x' | 'y'y
navcover height or widthnumber (Required)0

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;