wagmi icon indicating copy to clipboard operation
wagmi copied to clipboard

bug: `useContractsReads()` cause component re-render even if data hasn't changed

Open LilaRest opened this issue 3 years ago • 12 comments

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

  1. 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;
};
  1. 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

LilaRest avatar Aug 09 '23 16:08 LilaRest

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

LilaRest avatar Aug 09 '23 16:08 LilaRest

Ok, this happens when watch: true. I updated the Stackblitz and my initial message.

LilaRest avatar Aug 09 '23 18:08 LilaRest

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).

LilaRest avatar Aug 10 '23 08:08 LilaRest

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 avatar Aug 10 '23 09:08 LilaRest

@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 }

tmm avatar Aug 10 '23 15:08 tmm

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.

tmm avatar Aug 10 '23 15:08 tmm

@LilaRest you can also use the exported serialize and deserialize methods. ...

Good to know! Thanks.

Major update coming to address things like this.

That's great to hear! Any ETA?

Thanks for this amazing lib.

LilaRest avatar Aug 10 '23 15:08 LilaRest

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

anhthii avatar Aug 16 '23 14:08 anhthii

That's great to hear! Any ETA?

Would also like to know. Facing this issue right now.

bconfortin avatar Aug 29 '23 22:08 bconfortin

This is still a bug in 1.4.2 and make it quite problematic for any React app.

vblackwhale avatar Oct 14 '23 01:10 vblackwhale

Fixed by Wagmi v2

tmm avatar Jan 05 '24 16:01 tmm

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.

github-actions[bot] avatar Jan 20 '24 00:01 github-actions[bot]