Skip to content

Commit b1aca34

Browse files
authored
fix: useQuery() not reacting to query/param changes in StrictMode (#703)
1 parent e256286 commit b1aca34

File tree

3 files changed

+491
-498
lines changed

3 files changed

+491
-498
lines changed

.changeset/heavy-coats-serve.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@powersync/react': patch
3+
---
4+
5+
Fixed issue where `useQuery()` would not correctly trigger a new execution when the query or parameters changed while using StrictMode.

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ export const useWatchedQuery = <RowType = unknown>(
1616
): QueryResult<RowType> | ReadonlyQueryResult<RowType> => {
1717
const { query, powerSync, queryChanged, options: hookOptions, active } = options;
1818

19+
// This ref is used to protect against cases where `queryChanged` changes multiple times too quickly to be
20+
// picked up by the useEffect below. This typically happens when React.StrictMode is enabled.
21+
const queryChangeRef = React.useRef(false);
22+
if (queryChanged && !queryChangeRef.current) {
23+
queryChangeRef.current = true;
24+
}
25+
1926
function createWatchedQuery() {
2027
if (!active) {
2128
return null;
@@ -44,14 +51,15 @@ export const useWatchedQuery = <RowType = unknown>(
4451
// Indicates that the query will be re-fetched due to a change in the query.
4552
// Used when `isFetching` hasn't been set to true yet due to React execution.
4653
React.useEffect(() => {
47-
if (queryChanged) {
54+
if (queryChangeRef.current) {
4855
watchedQuery?.updateSettings({
4956
query,
5057
throttleMs: hookOptions.throttleMs,
5158
reportFetching: hookOptions.reportFetching
5259
});
60+
queryChangeRef.current = false;
5361
}
54-
}, [queryChanged]);
62+
}, [queryChangeRef.current]);
5563

5664
return useNullableWatchedQuerySubscription(watchedQuery);
5765
};

0 commit comments

Comments
 (0)