bug: `useContractsReads()` cause component re-render even if data hasn't changed
Is there an existing issue for this?
- [X] I have searched the existing issues
Package Version
1.3.9
Current Behavior
Including the useContractsReads() hook in a React component will lead to the component being re-rendered each time a new block is minted on-chain, even if the read data hasn't changed.
This leads to some components blinking on the interface.
This is also true when not arguments are passed to the hook and so when there is even no data to read.
Expected Behavior
The hook should trigger component re-render only when new data are available.
Steps To Reproduce
- Import and insert this component in a Wagmi project:
import { useContractReads } from 'wagmi';
export const TestComponent = () => {
const { data } = useContractReads({
watch: true,
});
console.log('RENDERING');
return null;
};
- Then watch the console. It should print "RENDERING" each time a new block is available.
Link to Minimal Reproducible Example (StackBlitz, CodeSandbox, GitHub repo etc.)
No response
Anything else?
No response
Just tried to reproduce it on Stackblitz and it seems to work as expected there: https://stackblitz.com/edit/new-wagmi-5e8ck3?file=src%2FApp.tsx
I'm closing for now, it should be project-related
Ok, this happens when watch: true. I updated the Stackblitz and my initial message.
Ok, so after some investigation I figured that it is caused by useContractReads({ watch: true }) and useContractRead({ watch: true }) relying on useBlockNumber({ watch: true }).
I managed to get around this by using watchReadContracts() in useEffect() and by setting state only if data has changed if it has changed. It looks like this:
import { watchReadContracts } from '@wagmi/core';
import { useEffect, useState } from 'react';
export const TestComponent = () => {
const [data, setData] = useState<any>();
useEffect(
() =>
watchReadContracts(
{
contracts: <your_reads_config>,
listenToBlock: true,
},
(newData) => {
// Update data only if it has changed
if (JSON.stringify(data) !== JSON.stringify(newData)) setData(newData);
},
),
[data, readsConfig],
);
console.log('RENDERING');
return null;
};
(The usage of any type for data here is just to make this code project-agnostic, not recommended in real use case).
I would love to see this natively implemented in Wagmi, this would highly improve the overhall performances. Re-rendering big components (like tables) every block may slow down page and cause blinking effect (like in my scenario).
Also, note that the usage of JSON.stringify() will raise an error if data contain some big numbers values. This can be easily solved by adding a custom replacer to the function.
export function JSONStringify(object: any) {
return JSON.stringify(
object,
(key, value) => (typeof value === "bigint" ? value.toString() : value),
);
}
See JSON.stringify() docs for more details.
@LilaRest you can also use the exported serialize and deserialize methods.
import { serialize, deserialize } from 'wagmi'
const serialized = serialize({ value: 69420n })
// '{"value":"#bigint.69420"}'
const deserialized = deserialize(serialized)
// { value: 69420n }
I would love to see this natively implemented in Wagmi, this would highly improve the overhall performances. Re-rendering big components (like tables) every block may slow down page and cause blinking effect (like in my scenario).
Major update coming to address things like this.
@LilaRest you can also use the exported
serializeanddeserializemethods. ...
Good to know! Thanks.
Major update coming to address things like this.
That's great to hear! Any ETA?
Thanks for this amazing lib.
I also faced this issue. Other parameter like enabled: false , cacheTime, staleTime doesn't work any more. It is spamming RPC and trigger a lot of rerendering
That's great to hear! Any ETA?
Would also like to know. Facing this issue right now.
This is still a bug in 1.4.2 and make it quite problematic for any React app.
Fixed by Wagmi v2
This issue has been locked since it has been closed for more than 14 days.
If you found a concrete bug or regression related to it, please open a new bug report with a reproduction against the latest wagmi version. If you have any other comments you can create a new discussion.