import { useEffect, useState } from "react"; import { useInputDevice } from "./use-input-device"; function getScrollbarWidth() { const outer = document.createElement("div"); outer.style.visibility = "hidden"; outer.style.overflow = "scroll"; document.body.appendChild(outer); const inner = document.createElement("div"); outer.appendChild(inner); const scrollbarWidth = outer.offsetWidth - inner.offsetWidth; outer.parentNode?.removeChild(outer); return scrollbarWidth; } export const useScrollbarWidth = () => { const inputDevice = useInputDevice(); // always return the same value first, so browser and server will get the same value and render the same thing const [width, setWidth] = useState(17); useEffect(() => { setWidth(getScrollbarWidth()); }, [inputDevice]); return width; };