disable react strict mode for event loop

This commit is contained in:
Khaleel Al-Adhami 2025-01-30 12:09:29 -08:00
parent 2c3257d4ea
commit cd7ccb3653
7 changed files with 69 additions and 30 deletions

View File

@ -38,13 +38,13 @@ export default function MyApp({ Component, pageProps }) {
}, []); }, []);
return ( return (
<ThemeProvider defaultTheme={ defaultColorMode } attribute="class"> <ThemeProvider defaultTheme={ defaultColorMode } attribute="class">
<AppWrap> <StateProvider>
<StateProvider> <EventLoopProvider>
<EventLoopProvider> <AppWrap>
<Component {...pageProps} /> <Component {...pageProps} />
</EventLoopProvider> </AppWrap>
</StateProvider> </EventLoopProvider>
</AppWrap> </StateProvider>
</ThemeProvider> </ThemeProvider>
); );
} }

View File

@ -301,10 +301,7 @@ export const applyEvent = async (event, socket) => {
// Send the event to the server. // Send the event to the server.
if (socket) { if (socket) {
socket.emit( socket.emit("event", event);
"event",
event,
);
return true; return true;
} }
@ -497,7 +494,7 @@ export const uploadFiles = async (
return false; return false;
} }
const upload_ref_name = `__upload_controllers_${upload_id}` const upload_ref_name = `__upload_controllers_${upload_id}`;
if (refs[upload_ref_name]) { if (refs[upload_ref_name]) {
console.log("Upload already in progress for ", upload_id); console.log("Upload already in progress for ", upload_id);
@ -833,6 +830,13 @@ export const useEventLoop = (
} }
})(); })();
} }
// Cleanup function.
return () => {
if (socket.current) {
socket.current.disconnect();
}
};
}); });
// localStorage event handling // localStorage event handling

View File

@ -54,6 +54,7 @@ from reflex.compiler.compiler import ExecutorSafeFunctions, compile_theme
from reflex.components.base.app_wrap import AppWrap from reflex.components.base.app_wrap import AppWrap
from reflex.components.base.error_boundary import ErrorBoundary from reflex.components.base.error_boundary import ErrorBoundary
from reflex.components.base.fragment import Fragment from reflex.components.base.fragment import Fragment
from reflex.components.base.strict_mode import StrictMode
from reflex.components.component import ( from reflex.components.component import (
Component, Component,
ComponentStyle, ComponentStyle,
@ -943,6 +944,12 @@ class App(MiddlewareMixin, LifespanMixin):
# If a theme component was provided, wrap the app with it # If a theme component was provided, wrap the app with it
app_wrappers[(20, "Theme")] = self.theme app_wrappers[(20, "Theme")] = self.theme
# Get the env mode.
config = get_config()
if config.react_strict_mode:
app_wrappers[(200, "StrictMode")] = StrictMode.create()
should_compile = self._should_compile() should_compile = self._should_compile()
for route in self._unevaluated_pages: for route in self._unevaluated_pages:
@ -977,9 +984,6 @@ class App(MiddlewareMixin, LifespanMixin):
+ adhoc_steps_without_executor, + adhoc_steps_without_executor,
) )
# Get the env mode.
config = get_config()
# Store the compile results. # Store the compile results.
compile_results = [] compile_results = []

View File

@ -0,0 +1,10 @@
"""Module for the StrictMode component."""
from reflex.components.component import Component
class StrictMode(Component):
"""A React strict mode component to enable strict mode for its children."""
library = "react"
tag = "StrictMode"

View File

@ -912,7 +912,6 @@ def _update_next_config(
next_config = { next_config = {
"basePath": config.frontend_path or "", "basePath": config.frontend_path or "",
"compress": config.next_compression, "compress": config.next_compression,
"reactStrictMode": config.react_strict_mode,
"trailingSlash": True, "trailingSlash": True,
"staticPageGenerationTimeout": config.static_page_generation_timeout, "staticPageGenerationTimeout": config.static_page_generation_timeout,
} }

View File

@ -1276,12 +1276,23 @@ def compilable_app(tmp_path) -> Generator[tuple[App, Path], None, None]:
yield app, web_dir yield app, web_dir
def test_app_wrap_compile_theme(compilable_app: tuple[App, Path]): @pytest.mark.parametrize(
"react_strict_mode",
[True, False],
)
def test_app_wrap_compile_theme(
react_strict_mode: bool, compilable_app: tuple[App, Path], mocker
):
"""Test that the radix theme component wraps the app. """Test that the radix theme component wraps the app.
Args: Args:
react_strict_mode: Whether to use React Strict Mode.
compilable_app: compilable_app fixture. compilable_app: compilable_app fixture.
mocker: pytest mocker object.
""" """
conf = rx.Config(app_name="testing", react_strict_mode=react_strict_mode)
mocker.patch("reflex.config._get_config", return_value=conf)
app, web_dir = compilable_app app, web_dir = compilable_app
app.theme = rx.theme(accent_color="plum") app.theme = rx.theme(accent_color="plum")
app._compile() app._compile()
@ -1292,24 +1303,37 @@ def test_app_wrap_compile_theme(compilable_app: tuple[App, Path]):
assert ( assert (
"function AppWrap({children}) {" "function AppWrap({children}) {"
"return (" "return ("
"<RadixThemesColorModeProvider>" + ("<StrictMode>" if react_strict_mode else "")
+ "<RadixThemesColorModeProvider>"
"<RadixThemesTheme accentColor={\"plum\"} css={{...theme.styles.global[':root'], ...theme.styles.global.body}}>" "<RadixThemesTheme accentColor={\"plum\"} css={{...theme.styles.global[':root'], ...theme.styles.global.body}}>"
"<Fragment>" "<Fragment>"
"{children}" "{children}"
"</Fragment>" "</Fragment>"
"</RadixThemesTheme>" "</RadixThemesTheme>"
"</RadixThemesColorModeProvider>" "</RadixThemesColorModeProvider>"
")" + ("</StrictMode>" if react_strict_mode else "")
+ ")"
"}" "}"
) in "".join(app_js_lines) ) in "".join(app_js_lines)
def test_app_wrap_priority(compilable_app: tuple[App, Path]): @pytest.mark.parametrize(
"react_strict_mode",
[True, False],
)
def test_app_wrap_priority(
react_strict_mode: bool, compilable_app: tuple[App, Path], mocker
):
"""Test that the app wrap components are wrapped in the correct order. """Test that the app wrap components are wrapped in the correct order.
Args: Args:
react_strict_mode: Whether to use React Strict Mode.
compilable_app: compilable_app fixture. compilable_app: compilable_app fixture.
mocker: pytest mocker object.
""" """
conf = rx.Config(app_name="testing", react_strict_mode=react_strict_mode)
mocker.patch("reflex.config._get_config", return_value=conf)
app, web_dir = compilable_app app, web_dir = compilable_app
class Fragment1(Component): class Fragment1(Component):
@ -1341,8 +1365,7 @@ def test_app_wrap_priority(compilable_app: tuple[App, Path]):
] ]
assert ( assert (
"function AppWrap({children}) {" "function AppWrap({children}) {"
"return (" "return (" + ("<StrictMode>" if react_strict_mode else "") + "<RadixThemesBox>"
"<RadixThemesBox>"
'<RadixThemesText as={"p"}>' '<RadixThemesText as={"p"}>'
"<RadixThemesColorModeProvider>" "<RadixThemesColorModeProvider>"
"<Fragment2>" "<Fragment2>"
@ -1352,8 +1375,7 @@ def test_app_wrap_priority(compilable_app: tuple[App, Path]):
"</Fragment2>" "</Fragment2>"
"</RadixThemesColorModeProvider>" "</RadixThemesColorModeProvider>"
"</RadixThemesText>" "</RadixThemesText>"
"</RadixThemesBox>" "</RadixThemesBox>" + ("</StrictMode>" if react_strict_mode else "") + ")"
")"
"}" "}"
) in "".join(app_js_lines) ) in "".join(app_js_lines)

View File

@ -32,7 +32,7 @@ runner = CliRunner()
app_name="test", app_name="test",
), ),
False, False,
'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', 'module.exports = {basePath: "", compress: true, trailingSlash: true, staticPageGenerationTimeout: 60};',
), ),
( (
Config( Config(
@ -40,7 +40,7 @@ runner = CliRunner()
static_page_generation_timeout=30, static_page_generation_timeout=30,
), ),
False, False,
'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 30};', 'module.exports = {basePath: "", compress: true, trailingSlash: true, staticPageGenerationTimeout: 30};',
), ),
( (
Config( Config(
@ -48,7 +48,7 @@ runner = CliRunner()
next_compression=False, next_compression=False,
), ),
False, False,
'module.exports = {basePath: "", compress: false, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', 'module.exports = {basePath: "", compress: false, trailingSlash: true, staticPageGenerationTimeout: 60};',
), ),
( (
Config( Config(
@ -56,7 +56,7 @@ runner = CliRunner()
frontend_path="/test", frontend_path="/test",
), ),
False, False,
'module.exports = {basePath: "/test", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', 'module.exports = {basePath: "/test", compress: true, trailingSlash: true, staticPageGenerationTimeout: 60};',
), ),
( (
Config( Config(
@ -65,14 +65,14 @@ runner = CliRunner()
next_compression=False, next_compression=False,
), ),
False, False,
'module.exports = {basePath: "/test", compress: false, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', 'module.exports = {basePath: "/test", compress: false, trailingSlash: true, staticPageGenerationTimeout: 60};',
), ),
( (
Config( Config(
app_name="test", app_name="test",
), ),
True, True,
'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60, output: "export", distDir: "_static"};', 'module.exports = {basePath: "", compress: true, trailingSlash: true, staticPageGenerationTimeout: 60, output: "export", distDir: "_static"};',
), ),
], ],
) )