Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: mo.lazy rendering (#1355)

Myles Scolnicke0e7c6230213
diff --git a/frontend/src/plugins/layout/LazyPlugin.tsx b/frontend/src/plugins/layout/LazyPlugin.tsx
index c6f7321a26..78c8f96bbf 100644
--- a/frontend/src/plugins/layout/LazyPlugin.tsx
+++ b/frontend/src/plugins/layout/LazyPlugin.tsx
@@ -7,7 +7,6 @@ import { useAsyncData } from "@/hooks/useAsyncData";
import { ErrorBanner } from "../impl/common/error-banner";
import { renderHTML } from "../core/RenderHTML";
import { useIntersectionObserver } from "@uidotdev/usehooks";
-import { useRef } from "react";
import { Loader2Icon } from "lucide-react";
interface Data {
@@ -21,7 +20,8 @@ type PluginFunctions = {
}>;
};
-type S = undefined;
+// Whether it has been loaded
+type S = boolean;
export const LazyPlugin = createPlugin<S>("marimo-lazy")
.withData(
@@ -36,28 +36,50 @@ export const LazyPlugin = createPlugin<S>("marimo-lazy")
}),
),
})
- .renderer((props) => <LazyComponent {...props.data} {...props.functions} />);
+ .renderer((props) => (
+ <LazyComponent
+ value={props.value}
+ setValue={props.setValue}
+ {...props.data}
+ {...props.functions}
+ />
+ ));
-type Props = PluginFunctions & Data;
+interface Props extends PluginFunctions, Data {
+ value: boolean;
+ setValue: (value: S) => void;
+}
-const LazyComponent = ({ load, showLoadingIndicator }: Props): JSX.Element => {
+const LazyComponent = ({
+ load,
+ showLoadingIndicator,
+ value,
+ setValue,
+}: Props): JSX.Element => {
const [ref, entry] = useIntersectionObserver({
threshold: 0,
root: null,
rootMargin: "0px",
});
- const hasIntersected = useRef<boolean>(false);
- if (entry?.isIntersecting) {
- hasIntersected.current = true;
+ if (entry?.isIntersecting && !value) {
+ setValue(true);
}
- const { data, loading, error } = useAsyncData(() => {
- if (!hasIntersected.current) {
- return Promise.resolve({ html: "" });
- }
- return load({});
- }, [hasIntersected.current]);
+ // For each re-render, we have to make a waterfall request
+ // We could improve performance if the BE was able to know if the same
+ // mo.lazy has already been loaded, and when re-rendering it would
+ // include the 'lazy' content by default (unlazily)
+ const { data, loading, error } = useAsyncData(
+ (ctx) => {
+ if (!value) {
+ ctx.previous();
+ return Promise.resolve(undefined);
+ }
+ return load({});
+ },
+ [value],
+ );
if (error) {
return <ErrorBanner error={error} />;
@@ -65,7 +87,7 @@ const LazyComponent = ({ load, showLoadingIndicator }: Props): JSX.Element => {
return (
<div ref={ref} className="min-h-4">
- {loading && showLoadingIndicator ? (
+ {loading && !data && showLoadingIndicator ? (
<Loader2Icon className="w-12 h-12 animate-spin text-primary my-4 mx-4" />
) : (
data && renderHTML({ html: data.html })
diff --git a/marimo/_plugins/stateless/lazy.py b/marimo/_plugins/stateless/lazy.py
index f0df4d0b9f..83d057b289 100644
--- a/marimo/_plugins/stateless/lazy.py
+++ b/marimo/_plugins/stateless/lazy.py
@@ -17,7 +17,7 @@ class LoadResponse:
@mddoc
-class lazy(UIElement[None, None]):
+class lazy(UIElement[bool, bool]):
"""Lazy load a component until it is visible.
Use `mo.lazy` to defer rendering of an item until it's visible. This is
@@ -79,12 +79,12 @@ class lazy(UIElement[None, None]):
super().__init__(
component_name=self._name,
- initial_value=None,
+ initial_value=False,
label="",
args={
"show-loading-indicator": show_loading_indicator,
},
- on_change=lambda _: None,
+ on_change=None,
functions=(
Function(
name=self.load.__name__,
@@ -94,7 +94,7 @@ class lazy(UIElement[None, None]):
),
)
- def _convert_value(self, value: None) -> None:
+ def _convert_value(self, value: bool) -> bool:
return value
async def load(self, _args: EmptyArgs) -> LoadResponse:
diff --git a/marimo/_smoke_tests/lazy.py b/marimo/_smoke_tests/lazy.py
index e65be2ad60..d41d9f8bf2 100644
--- a/marimo/_smoke_tests/lazy.py
+++ b/marimo/_smoke_tests/lazy.py
@@ -2,15 +2,21 @@
import marimo
-__generated_with = "0.4.10"
+__generated_with = "0.5.2"
app = marimo.App(width="full")
@app.cell
-def __(generate_number, mo, table):
+def __(mo):
+ slider = mo.ui.slider(0, 10)
+ return slider,
+
+
+def __(generate_number, mo, slider, table):
tabs = mo.ui.tabs(
{
- "First": "",
+ "First": [slider, slider.value],
"Second": mo.lazy(table),
"Third": mo.lazy(generate_number, show_loading_indicator=True),
}
@@ -20,10 +26,10 @@ def __(generate_number, mo, table):
@app.cell
-def __(generate_number, mo, table):
+def __(generate_number, mo, slider, table):
auto_lazy_tabs = mo.ui.tabs(
{
- "First": "",
+ "First": [slider, slider.value],
"Second": table,
"Third": generate_number,
},