CraZyDroiD
CraZyDroiD

Reputation: 7105

prevent re-render using useMemo

I am doing a fetch every 30 seconds and saving the response in my redux state. What i want to do is prevent re rendering of the component if the response is same as the previous one. To do this i have tried useMemo hook.

const details = useSelector((state: RootState) => state.orders.details);

This is the state i'm updating every 30 seconds. (Which is an object)

This is how i implemented useMemo

const memorizedDetails = useMemo(() => {
    return details;
  }, [details]);

And finally my useEffect

  useEffect(() => {
    if (memorizedOrderDetails) {
      console.log("content changed");
    }
  }, [memorizedOrderDetails]);

But even if the updated detail is same as the previous one, it always logs "content changed" every 30 seconds.

Is the way i'm using the useMemo wrong here?

Upvotes: 0

Views: 853

Answers (1)

Taha LAGHZALI
Taha LAGHZALI

Reputation: 534

I suggest to you to use reselect in order to memoize selectors, so if there is no changes it won't render

Here is the link of reselect : https://github.com/reduxjs/reselect

Upvotes: 1

Related Questions