Skip to content

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