SolaraViz: move hooks before early return in ComponentsView#2925
SolaraViz: move hooks before early return in ComponentsView#2925
Conversation
This comment was marked as off-topic.
This comment was marked as off-topic.
|
@Sahil-Chhoker, can you help out with this? The warning seems to originate from A potential fix could be to move @solara.component
def ComponentsView(components, model):
current_tab_index, set_current_tab_index = solara.use_state(0)
layouts, set_layouts = solara.use_state({})
def sync_layouts():
if not components:
return
# ... build pages and sync logic here ...
solara.use_effect(sync_layouts, [len(components)] if components else [])
if not components: # Now safe to return early
return
# ... rest of component ...This would make sure all hooks are called in the same order on every render. Does this have any negative effects? The early return was meant for something I can imagine. |
|
@Sahil-Chhoker if you have the chance, could you take a look at this? |
Sahil-Chhoker
left a comment
There was a problem hiding this comment.
I don’t think this should cause any issues. I tested all the examples and didn’t encounter any problems, so it’s good to go.
|
Thanks for your comments. I don’t think the PR resolve this issue fully (see comment above), and I don’t knop what exactly is happening and what should be happening. |
Moves solara.use_state() calls before the early return to comply with React's Rules of Hooks. Hooks must be called in the same order on every render and cannot be conditional. Fixes Solara hooks validation warning (SH101).
Moves solara.use_state() calls before the early return to comply with React's Rules of Hooks. Hooks must be called in the same order on every render and cannot be conditional. Fixes Solara hooks validation warning (SH101).
|
To a fresh stab at it and the warning is now gone. Merging. |
Problem
The
ComponentsViewcomponent insolara_viz.pywas violating Solara's Rules of Hooks (rule SH101: early return). The component had an early return statement when thecomponentslist was empty, but hook calls (use_stateanduse_effect) were placed after this conditional return. This caused the following warning during execution:This violation occurs because hooks must be called in the same order on every render to maintain proper state management. When
componentsis empty, the function returns early and skips all hook calls. Whencomponentsis not empty, the hooks are executed. This inconsistency can lead to state slots becoming misaligned between renders, potentially causing bugs and unexpected behavior.Solution
This PR restructures the
ComponentsViewcomponent to ensure all hooks (use_stateanduse_effect) are called at the top level before the early return statement. The empty components check has been moved inside thesync_layoutseffect callback, allowing the hook to be called consistently on every render while still handling the empty case appropriately.Testing
Warning is gone.
References