Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 31 additions & 25 deletions reflex/compiler/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def app_root_template(
return f"""
{imports_str}
{dynamic_imports_str}
import {{ EventLoopProvider, StateProvider, defaultColorMode }} from "$/utils/context";
import {{ EventLoopProvider, StatesProvider, defaultColorMode }} from "$/utils/context";
import {{ ThemeProvider }} from '$/utils/react-theme';
import {{ Layout as AppLayout }} from './_document';
import {{ Outlet }} from 'react-router';
Expand All @@ -226,7 +226,7 @@ def app_root_template(

return jsx(AppLayout, {{}},
jsx(ThemeProvider, {{defaultTheme: defaultColorMode, attribute: "class"}},
jsx(StateProvider, {{}},
jsx(StatesProvider, {{}},
jsx(EventLoopProvider, {{}},
jsx(AppWrap, {{}}, children)
)
Expand Down Expand Up @@ -327,22 +327,12 @@ def context_template(
"""
)

state_reducer_str = "\n".join(
rf'const [{format_state_name(state_name)}, dispatch_{format_state_name(state_name)}] = useReducer(applyDelta, initialState["{state_name}"])'
for state_name in initial_state
)

create_state_contexts_str = "\n".join(
rf"createElement(StateContexts.{format_state_name(state_name)},{{value: {format_state_name(state_name)}}},"
rf"createElement(StateProvider, {{state_name: '{state_name}', ctx_name: '{format_state_name(state_name)}'}}, "
for state_name in initial_state
)

dispatchers_str = "\n".join(
f'"{state_name}": dispatch_{format_state_name(state_name)},'
for state_name in initial_state
)

return rf"""import {{ createContext, useContext, useMemo, useReducer, useState, createElement, useEffect }} from "react"
return rf"""import {{ createContext, useContext, useMemo, useReducer, useRef, useState, createElement, useEffect }} from "react"
import {{ applyDelta, ReflexEvent, hydrateClientStorage, useEventLoop, refs }} from "$/utils/state"
import {{ jsx }} from "@emotion/react";

Expand Down Expand Up @@ -402,19 +392,35 @@ def context_template(
);
}}

export function StateProvider({{ children }}) {{
{state_reducer_str}
const dispatchers = useMemo(() => {{
return {{
{dispatchers_str}
}}
}}, [])
const DispatchProvider = ({{ children }}) => {{
const dispatchers = useRef({{}});
return useMemo(() => createElement(DispatchContext, {{ value: dispatchers }}, children), [children, dispatchers]);
Comment on lines +395 to +397
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ref object used as plain dictionary

DispatchProvider passes the useRef({}) return value (a ref object with shape { current: {} }) as the context value. Then in StateProvider (line 404), dispatchers are set directly on this ref object (dispatchers[state_name] = dispatch_state) rather than on dispatchers.current. Similarly, EventLoopProvider and state.js access dispatch[substate] directly.

This works because the ref object is a stable mutable JS object, but it's unconventional — the .current property initialized to {} goes unused, and properties are set directly on the ref itself. A plain useRef(null) or useMemo(() => ({}), []) would make the intent clearer. Alternatively, if .current is meant to be the container, both the reads and writes should go through .current:

const DispatchProvider = ({ children }) => {
  const dispatchers = useRef({});
  return useMemo(() => createElement(DispatchContext, { value: dispatchers.current }, children), [children, dispatchers]);
}

…and update StateProvider to match (dispatchers.current[state_name] = ...).

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

}}

return (
{create_state_contexts_str}
createElement(DispatchContext, {{value: dispatchers}}, children)
const StateProvider = ({{ children, state_name, ctx_name }}) => {{
const dispatchers = useContext(DispatchContext);
const [state, dispatch_state] = useReducer(applyDelta, initialState[state_name]);
useEffect(() => {{
dispatchers[state_name] = dispatch_state;
return () => delete dispatchers[state_name];
}}, [dispatchers, dispatch_state, state_name]);
return useMemo(
() =>
createElement(
StateContexts[ctx_name],
{{ value: state }},
children,
),
[children, state, ctx_name],
);
}}
Comment on lines +400 to +416
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dispatcher registration via useEffect creates a timing gap

Each StateProvider registers its dispatcher in a useEffect (line 403-405). Since useEffect runs after paint and React commits effects bottom-up (children first), the EventLoopProvider's socket-connecting effect (in state.js line 997-1011) fires before the StateProvider effects that register dispatchers.

In practice, the websocket connection is async so dispatchers are likely registered by the time the first "event" message arrives. However, if the socket connects very quickly (e.g. reconnect scenario), state.js line 681 (dispatch[substate](...)) could throw a TypeError because the dispatcher for that substate isn't registered yet on the ref object.

Consider using useLayoutEffect instead of useEffect for the dispatcher registration to ensure dispatchers are available synchronously after render, before any child effects or event handlers run.


export function StatesProvider({{ children }}) {{
return useMemo(() => (
createElement(DispatchProvider, {{}},
{create_state_contexts_str}children
{")" * len(initial_state)}
)
)), [children])
}}"""


Expand Down
Loading