Cannot get React to complain about a non-pure function

35 Views Asked by At

I was reading the official docs on: https://react.dev/learn/keeping-components-pure#detecting-impure-calculations-with-strict-mode

It talks about using:

  <StrictMode>
    <App />
  </StrictMode>

to guard against functions that are accidentally written not as pure function.

So I wrote some components that intentionally break the rules:

let bar = 1;

function Foo({ hmm }) {
  console.log("IN Foo");

  bar += Math.random();
  hmm += Math.random();

  return (
    <div>
      hmm is {hmm}, bar is {bar}
    </div>
  );
}

function App() {
  console.log("IN APP");

  bar += 10 + Math.random();

  return (
    <>
      <div>hi {bar}</div>
      <Foo hmm={123} />
      <Foo hmm={456} />
    </>
  );
}

export default App;

However, I cannot get React to warn or give an error about it. So what is the purpose of <StrictMode> if it doesn't give any warning?

1

There are 1 best solutions below

4
Unmitigated On

StrictMode is not meant to provide a warning; rather, it intentionally renders the component twice so that you, the developer, can notice that it might not behave as you intended.

You can see this from the same linked documentation:

Notice how the original example displayed “Guest #2”, “Guest #4”, and “Guest #6” instead of “Guest #1”, “Guest #2”, and “Guest #3”. The original function was impure, so calling it twice broke it.