1

I wonder why does calling React useState causes functional component to be executed twice. Please see an example.

Instantiating a Dummy component with a following body:

const Dummy = () => {

  console.log('[Dummy] starting');

  return (
    <p>Dummy</p>
  )
};

Outputs:

[App] start
[Dummy] starting

But for a following body:

const Dummy = () => {

  const [loading, setLoading] = useState(false);
  console.log('[Dummy] starting');

  return (
    <p>Dummy</p>
  )
};

Console shows:

[App] start
[Dummy] starting
[Dummy] starting

Common parent code for both cases:

const app = () => {
  console.log('[App] start');
  return (
    <Dummy />
  );
};

Thanks.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
luki
  • 29
  • 2

0 Answers0