Skip to content

Commit fcb67fb

Browse files
committed
fix lazy components
1 parent 572f0ed commit fcb67fb

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

reflex/.templates/jinja/web/utils/context.js.jinja2

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { createContext, useContext, useMemo, useReducer, useState, createElement } from "react"
1+
import { createContext, useContext, useMemo, useReducer, useState, createElement, useEffect } from "react"
22
import { applyDelta, Event, hydrateClientStorage, useEventLoop, refs } from "$/utils/state"
3+
import { jsx } from "@emotion/react";
34

45
{% if initial_state %}
56
export const initialState = {{ initial_state|json_dumps }}
@@ -84,6 +85,16 @@ export function UploadFilesProvider({ children }) {
8485
);
8586
}
8687

88+
export function ClientSide(component) {
89+
return ({ children, ...props }) => {
90+
const [Component, setComponent] = useState(null);
91+
useEffect(() => {
92+
setComponent(component);
93+
}, []);
94+
return Component ? jsx(Component, props, children) : null;
95+
};
96+
}
97+
8798
export function EventLoopProvider({ children }) {
8899
const dispatch = useContext(DispatchContext)
89100
const [addEvents, connectErrors] = useEventLoop(

reflex/components/component.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from rich.markup import escape
2020

2121
import reflex.state
22+
from reflex import constants
2223
from reflex.base import Base
2324
from reflex.compiler.templates import STATEFUL_COMPONENT
2425
from reflex.components.core.breakpoints import Breakpoints
@@ -1982,7 +1983,10 @@ def _get_imports(self) -> ParsedImportDict:
19821983
The imports for dynamically importing the component at module load time.
19831984
"""
19841985
# Next.js dynamic import mechanism.
1985-
dynamic_import = {"react": [ImportVar(tag="lazy")]}
1986+
dynamic_import = {
1987+
"react": [ImportVar(tag="lazy")],
1988+
f"$/{constants.Dirs.UTILS}/context": [ImportVar(tag="ClientSide")],
1989+
}
19861990

19871991
# The normal imports for this component.
19881992
_imports = super()._get_imports()
@@ -2015,10 +2019,10 @@ def _get_dynamic_imports(self) -> str:
20152019
else ""
20162020
)
20172021
return (
2018-
f"const {self.alias if self.alias else self.tag} = lazy(() => "
2022+
f"const {self.alias if self.alias else self.tag} = ClientSide(lazy(() => "
20192023
+ library_import
20202024
+ mod_import
2021-
+ ")"
2025+
+ "))"
20222026
)
20232027

20242028

0 commit comments

Comments
 (0)