Skip to content

useMemo docs state that value will be computed when a new functions instance is passed which is not true #1796

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 14, 2019

Conversation

DimitarNestorov
Copy link
Contributor

@DimitarNestorov DimitarNestorov commented Mar 8, 2019

The docs say that

a new value will be computed whenever a new function instance is passed as the first argument

The following code shows otherwise. The function instance is always the same, however a new value for n is computed on every render because no array is passed.

import React, { useMemo, useState } from "react";
import ReactDOM from "react-dom";

class RandomNumberContainer {
  number = Math.random();
}

function createRandomNumberContainer() {
  return new RandomNumberContainer();
}

function App() {
  const [i, setI] = useState(0);
  const n = useMemo(createRandomNumberContainer);
  const n2 = useMemo(createRandomNumberContainer, []);

  return (
    <div className="App">
      <p>i: {i}</p>
      <p>number: {n.number}</p>
      <p>number2: {n2.number}</p>
      <button onClick={() => setI(i + 1)} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Here's an example sandbox: https://codesandbox.io/s/4x68k8nrw

@reactjs-bot
Copy link

Deploy preview for reactjs ready!

Built with commit ec2c7f2

https://deploy-preview-1796--reactjs.netlify.com

@gaearon gaearon merged commit 40bbbd5 into reactjs:master Mar 14, 2019
@gaearon
Copy link
Member

gaearon commented Mar 14, 2019

You're right. :-( This behavior changed from alphas to stable but we missed this during the docs update. Sorry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants