Skip to content

Avoid calling hooks conditionally#697

Merged
simolus3 merged 1 commit into
mainfrom
unconditional-react-hooks
Aug 20, 2025
Merged

Avoid calling hooks conditionally#697
simolus3 merged 1 commit into
mainfrom
unconditional-react-hooks

Conversation

@simolus3

Copy link
Copy Markdown
Contributor

In useQuery, we used to invoke the inner useWatchedQuery or useSingleQuery hooks depending on options passed to the useQuery hook.

This violates the rules of hooks, because they must be invoked unconditionally. Mixing them like this can trip up the internal state of useEffect hooks and others, causing all kinds of issues that are hard to debug.

So to avoid this, we add an active: boolean parameter to the internal hooks to conditionally disable them. Then, we can just call both hooks all the time since the inactive one won't actually do anything. I've added a test that fails with the old implementation but works with the new one.

@changeset-bot

changeset-bot Bot commented Aug 20, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: b364169

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@powersync/react Patch
@powersync/react-native Patch
@powersync/tanstack-react-query Patch
@powersync/diagnostics-app Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Comment thread packages/react/src/hooks/watched/useWatchedQuery.ts

@stevensJourney stevensJourney left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I initially didn't think there was much of a use-case for switching the runQueryOnce setting, but this is a good improvement which does cater for changing the behaviour (which some users do implement). I'm happy with the changes here.

@simolus3 simolus3 merged commit 8decd49 into main Aug 20, 2025
9 checks passed
@simolus3 simolus3 deleted the unconditional-react-hooks branch August 20, 2025 11:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants