diff --git a/.changeset/fifty-sheep-battle.md b/.changeset/fifty-sheep-battle.md new file mode 100644 index 0000000000..30fab153c6 --- /dev/null +++ b/.changeset/fifty-sheep-battle.md @@ -0,0 +1,5 @@ +--- +'urql': patch +--- + +Avoid unnecessary re-render when two components use the same query but receive unchanging results, due to differing operations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e263eb7dad..6d47c40a29 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,7 +75,7 @@ There are multiple commands you can run in the root folder to test your changes: ```sh # TypeScript checks: -pnpnm run check +pnpm run check # Linting (prettier & eslint): pnpm run lint diff --git a/packages/react-urql/src/hooks/state.ts b/packages/react-urql/src/hooks/state.ts index c145b47748..bf8d4f4ad3 100644 --- a/packages/react-urql/src/hooks/state.ts +++ b/packages/react-urql/src/hooks/state.ts @@ -9,10 +9,29 @@ export const initialState = { operation: undefined, }; -const isShallowDifferent = (a: any, b: any) => { - if (typeof a != 'object' || typeof b != 'object') return a !== b; - for (const x in a) if (!(x in b)) return true; - for (const x in b) if (a[x] !== b[x]) return true; +// Two operations are considered equal if they have the same key +const areOperationsEqual = ( + a: { key: number } | undefined, + b: { key: number } | undefined +) => { + return a === b || !!(a && b && a.key === b.key); +}; + +/** + * Checks if two objects are shallowly different with a special case for + * 'operation' where it compares the key if they are not the otherwise equal + */ +const isShallowDifferent = >(a: T, b: T) => { + for (const key in a) if (!(key in b)) return true; + for (const key in b) { + if ( + key === 'operation' + ? !areOperationsEqual(a[key], b[key]) + : a[key] !== b[key] + ) { + return true; + } + } return false; }; @@ -27,7 +46,7 @@ export const computeNextState = ( prevState: T, result: Partial ): T => { - const newState = { + const newState: T = { ...prevState, ...result, data: