diff --git a/.changeset/two-plants-thank.md b/.changeset/two-plants-thank.md new file mode 100644 index 00000000..fe247b1b --- /dev/null +++ b/.changeset/two-plants-thank.md @@ -0,0 +1,6 @@ +--- +"@powersync/common": patch +"@powersync/react": patch +--- + +chore: optimize the useStatus hook and underlying isEqual diff --git a/packages/common/src/db/crud/SyncStatus.ts b/packages/common/src/db/crud/SyncStatus.ts index 59080a49..7e5c9b22 100644 --- a/packages/common/src/db/crud/SyncStatus.ts +++ b/packages/common/src/db/crud/SyncStatus.ts @@ -11,7 +11,7 @@ export type SyncStatusOptions = { }; export class SyncStatus { - constructor(protected options: SyncStatusOptions) {} + constructor(protected options: SyncStatusOptions) { } /** * true if currently connected. @@ -56,7 +56,18 @@ export class SyncStatus { } isEqual(status: SyncStatus) { - return JSON.stringify(this.options) == JSON.stringify(status.options); + if (!status) return false; + + const thisOpts = this.options; + const otherOpts = status.options; + + return ( + thisOpts.connected === otherOpts.connected && + thisOpts.hasSynced === otherOpts.hasSynced && + (thisOpts.lastSyncedAt?.getTime() === otherOpts.lastSyncedAt?.getTime()) && + thisOpts.dataFlow?.downloading === otherOpts.dataFlow?.downloading && + thisOpts.dataFlow?.uploading === otherOpts.dataFlow?.uploading + ); } getMessage() { diff --git a/packages/react/src/hooks/usePowerSyncStatus.ts b/packages/react/src/hooks/usePowerSyncStatus.ts index 0798db66..28359ee9 100644 --- a/packages/react/src/hooks/usePowerSyncStatus.ts +++ b/packages/react/src/hooks/usePowerSyncStatus.ts @@ -21,10 +21,13 @@ export const usePowerSyncStatus = () => { useEffect(() => { const listener = powerSync.registerListener({ - statusChanged: (status) => { - setSyncStatus(status); + statusChanged: (newStatus) => { + setSyncStatus(prev => { + // Only update if the status is actually different + return prev.isEqual(newStatus) ? prev : newStatus + }) } - }); + }) return () => listener?.(); }, [powerSync]);