Skip to content

Instantly share code, notes, and snippets.

@codemile
Created July 8, 2021 11:09
Show Gist options
  • Save codemile/3c22f75d397538d87b19d4ecc86d4c22 to your computer and use it in GitHub Desktop.
Save codemile/3c22f75d397538d87b19d4ecc86d4c22 to your computer and use it in GitHub Desktop.
Hook that reads/writes #CSS variables. Turns a CSS variable into a useState() hook for your web components and lets you change them at run-time.
export const useCSSVariable = (name: string) => {
const [value, setState] = useState(
window.getComputedStyle(document.documentElement).getPropertyValue(name)
);
const setValue = useCallback(
(newValue: string) => {
setState(newValue);
document.documentElement.style.setProperty(name, newValue);
},
[name]
);
return [value, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment