Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

memoize globalCss using ref

Oleg Isonen55a5d7891ed3
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsx
index 52b7ebb6a8..2c00da02c4 100644
--- a/apps/designer/app/canvas/canvas.tsx
+++ b/apps/designer/app/canvas/canvas.tsx
@@ -117,7 +117,7 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
}
const isDesignerReady = useSubscribeDesignerReady();
useInitializeBreakpoints(data.breakpoints);
- useGlobalStyles({ assets: data.assets })();
+ useGlobalStyles({ assets: data.assets });
useAllUserProps(data.props);
usePopulateRootInstance(data.tree);
// e.g. toggling preview is still needed in both modes
diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.ts
index 1b2dbd6c20..8cd2f1dc28 100644
--- a/packages/react-sdk/src/tree/root.ts
+++ b/packages/react-sdk/src/tree/root.ts
@@ -9,7 +9,7 @@ import {
} from "./wrapper-component";
import { FONT_FORMATS, getFontFaces } from "@webstudio-is/fonts";
import type { Asset, FontAsset } from "@webstudio-is/asset-uploader";
-import { useCallback } from "react";
+import { useRef } from "react";
export type Data = {
tree: Tree | null;
@@ -19,18 +19,24 @@ export type Data = {
};
export const useGlobalStyles = ({ assets }: { assets: Array<Asset> }) => {
- return useCallback(() => {
- const fontAssets = assets.filter(
- (asset) => asset.format in FONT_FORMATS
- ) as Array<FontAsset>;
-
- return globalCss({
- "@font-face": getFontFaces(fontAssets),
- html: {
- height: "100%",
- },
- })();
- }, [assets]);
+ const ref = useRef<Array<Asset>>();
+
+ // This may look weird, but globalCss API doesn't allow us creating global styles with data,
+ // so we have to manually ensure calling it only once
+ if (ref.current === assets) return;
+
+ const fontAssets = assets.filter(
+ (asset) => asset.format in FONT_FORMATS
+ ) as Array<FontAsset>;
+
+ globalCss({
+ "@font-face": getFontFaces(fontAssets),
+ html: {
+ height: "100%",
+ },
+ })();
+
+ ref.current = assets;
};
type RootProps = {
@@ -46,7 +52,7 @@ export const InstanceRoot = ({
throw new Error("Tree is null");
}
setBreakpoints(data.breakpoints);
- useGlobalStyles({ assets: data.assets })();
+ useGlobalStyles({ assets: data.assets });
useAllUserProps(data.props);
return createElementsTree({
instance: data.tree.root,