use-global-css.ts 727 B

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. import { useEffect } from 'react';
  6. interface UseGlobalCSSOptions {
  7. cssText: string;
  8. id: string;
  9. cleanup?: boolean;
  10. }
  11. export const useGlobalCSS = ({ cssText, id, cleanup }: UseGlobalCSSOptions) => {
  12. useEffect(() => {
  13. /** SSR safe */
  14. if (typeof document === 'undefined') return;
  15. if (document.getElementById(id)) return;
  16. const style = document.createElement('style');
  17. style.id = id;
  18. style.textContent = cssText;
  19. document.head.appendChild(style);
  20. return () => {
  21. const existing = document.getElementById(id);
  22. if (existing && cleanup) existing.remove();
  23. };
  24. }, [id]);
  25. };