-1

In the following minimum working example of App.js:

import { useState, useEffect } from "react";


export default function App() {
  const [isShown, setIsShown] = useState(true);
  return (
    <>
      <button onClick = {() => setIsShown(!isShown)}>
        {isShown? 'Hide Counter' : 'Show Counter'}
      </button>
      {isShown? <Counter /> : null}
    </>
  );
}

function Counter(){
  const [count, setCount] = useState(0);
  const [bool, setBool] = useState(false);

  useEffect(() => {
    console.log('render');
  });
  
  useEffect(() => {
      console.log('mounted');
    }, []);
  return (
    <div className="counter">
      <button onClick={() =>setBool(!bool)}>Re-Render</button>
      <button onClick={() =>setCount(count + 1)}>Increment</button>
      <p> Count: {count}</p>
    </div>
  );
}

I get two sets of console.logs (i.e. the messages "render" and "mounted" show up twice) whenever I refresh the page or when I click on "Hide Counter" and then click on "Show Counter". My expectation is that "render" and "show" should show up only once. In the current case, this seems to imply that the components are rendering two times every time the page loads. I've tested this on Firefox and Chrome and find the same behavior in both.

Why is this and how can I begin to debug this?

vikram-s-narayan
  • 538
  • 4
  • 12

1 Answers1

0

This is because of React strict mode, if you remove it from your index file, you don't get two renders.

Farnam H
  • 192
  • 2
  • 6