1

I am using useMemo react hook in the function component. I am not sure why the console log is getting twice printed. Here below is my code:

import './App.css';
import react,{useState,useMemo} from 'react';

function App() {

  const [count,setCount] = useState(0);
  const [item,setItem] = useState(10);

  const multiCountMemo = useMemo(function multiCount() {
    console.log("to check if getting inside the function")  <---- this is getting printed twice by default on load app page.
    return count * 5
  },[count])


  return (
    <div className="App">
      <h1>useMemo Hook Usage</h1>

      <h2>Count : {count}</h2>
      
      <h2>Item : {item}</h2>

      <h2>{multiCountMemo}</h2>

      <button onClick={() => setCount(count + 1)}>Update Count</button>
      
      <button onClick={() => setItem(item * 10)}>Update Item</button>
    </div>
  );
}

export default App;

enter image description here

3
  • Does this answer your question? Why my render method is react called twice Commented May 20, 2022 at 12:03
  • which react version are you on? Commented May 20, 2022 at 13:06
  • I am using "react": "^18.1.0", Commented May 20, 2022 at 13:28

1 Answer 1

3

This is due to strict mode – check the docs here.

useEffect in React version 18 causes the component to unmount and mount again after it mounts the first time. This is why the console.log is triggering twice.

note that this only happens in development mode and not production react docs showing strict mode

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.