Next.js Discord

Discord Forum

Can you help me explain why useMemo doesn't function as a cache?

Unanswered
Longtail tuna posted this in #help-forum
Open in Discord
Longtail tunaOP
I saw two sentences in the document:
https://react.dev/reference/react/use#caveats
1. use re-renders the component after the data is resolved.
Question: Why is useMemo executed again when re-rendering? How to understand re-render here?
2. Promises created in Client Components are recreated on every render.
Question : How to understand this sentence

Demo : https://codesandbox.io/p/sandbox/react-dev-forked-8fpjhd?workspaceId=ws_HRgeaCc4c14UUVZk6sijk9

code:

import { use, Suspense, useMemo } from "react";
function generateRandomString(length) {
  let result = "";
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const charactersLength = characters.length;

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}
let prevPromise = null;
function Message({ messagePromise }) {
  
  if (!messagePromise) {
    return <p> messagePromise is null</p>;
  }
  console.log("render message ");
  console.log(
    "prevPromise",
    prevPromise,
    "messagePromise",
    messagePromise,
    prevPromise === messagePromise
  );
  prevPromise = messagePromise;
  const person = useMemo(() => {
    return {
      name: generateRandomString(4),
    };
  }, []);
  //The person's name has a different value every time you render. Why??
  console.log("person", person);
  const messageContent = use(messagePromise);
  console.log("after use messagePromise");
  return <p>Here is the message: {messageContent}</p>;
}

8 Replies

Why is useMemo executed again when re-rendering? How to understand re-render here?
There isn't a mention of useMemo in that article. The main point is that you shouldn't use use() in server components.

Promises created in Client Components are recreated on every render.
Article is suggesting you create the promise from parent component and pass it down to a component like this

const getDataPromise = getData(index)
return <ClientComp getDataPromise={getDataPromise} />

and

const data = use(props.getDataPromise)
It looks as if useMemo did not successfully cache the person object
Longtail tunaOP
Is anyone interested in this question?