3

I found a behavior where the generator appears to be called twice.

The following is a simple code that gets a number from the generator and output it to console. It expects 0 and 1 to be output to the console, but in fact it outputs 0 and 2.

import { useState, useEffect } from "react";
 
function* counter() {
  let val = 0;
  while (true) yield val++;
}
const count = counter();

function App() {
  console.log("rendered: count = ", count.next().value);
  const [hoge, setHoge] = useState("first");
  console.log("rendered:", hoge);

  useEffect(() => setHoge("second"), [setHoge]);
  return <div>{hoge}</div>;
}

export default App;

demo: https://codesandbox.io/s/friendly-http-g84cp?file=/src/App.tsx

Not only to useEffect, I also found the same behavior with setInterval. Also, if we remove <React.strict>, the console outputs 0 and 1 as expected.

Do you have any idea why this behavior is happening?

3
  • why did you put setHoge in dependency array of useEffect ? it should be hoge
    – miraj
    May 26, 2021 at 17:21
  • Wouldn't that cause infinite updates, since every time the hoge is updated, the useEffect updates the hoge?
    – noyan
    May 26, 2021 at 18:26
  • no that wouldn't cause infinite updates. useEffect checks the state variable not state updater function(setHoge).
    – miraj
    May 26, 2021 at 18:45

2 Answers 2

4

As per the docs,

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

That Function component bodies being invoked twice is the cause of your problem. That means on initial mount, App function body will be invoked twice and then again on setting a new state, App function body will be invoked twice. By that logic, you should have seen 4 more logs i.e 8 in total.

Here is where the following exception comes :-

Starting with React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions. However, it may cause undesired behavior in certain cases where a workaround can be used.

To actually visualize all the 8 logs, you can just do let log = console.log at the top level and replace usage of console.log by log and you will see what's actually happening.

Simply said, don't put such a behavior inside a function body since it's a side-effect for which Strict-mode came into being.

Here is a forked codesandbox to see this :-

Edit dreamy-aryabhata-ddzyz

1
  • Thanks for the detailed explanation! I now understand the cause: Strict mode is deliberately reading the application twice to detect side effects. That's pretty interesting.
    – noyan
    May 26, 2021 at 18:17
1

The <React.StrictMode> exists to detect precisely what you're doing in your code which is an anti-pattern (side-effect in the render function).

This mode executes the lifecycle methods of the components twice on purpose (in your case it's a functional component so the function is being executed twice), while swallowing the console.log by monkeypatching it.

That's why you observe the generator increment without any log in the console.

1
  • 1
    The side effects are caused by the implementation of the counter as a generator. I didn't notice it, though it is obvious now. Thank you very much!
    – noyan
    May 26, 2021 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.