1

Console.log runs twice. Underneath said it is to reason Strict Mode:

React Hooks: useEffect() is called twice even if an empty array is used as an argument

StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).

But I don't understand why! It says: in order to detect any problems with your code and warn you about them. But which is the problem? And warning about what thing?

And is there a way for rid of that(twice running) without removing Strict Mode from the app?

It's my code:

import {useEffect, useState} from "react";
import BlogList from "./BlogList";

const Home = () =>{
    const [blogs, setBlogs] = useState([
        { title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },
        { title: 'Welcome party!', body: 'lorem ipsum...', author: 'yoshi', id: 2 },
        { title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }
    ]);
    const [name, setName] = useState('mario');
    const handleDelete = (id) => {
        const newBlogs = blogs.filter(blog => blog.id !== id);
        setBlogs(newBlogs);
    }
    useEffect(() => {
        console.log("useEffect is run");
        console.log(name);
    },[name]);
    return(
        <div className="Home">
            <BlogList blogs={blogs} title="All Blogs" handleDelete={handleDelete} />
            <button onClick={() => setName('arman')}>Delete name</button>
            <p>{name}</p>
        </div>
    );
}

export default Home;

The complete code:

https://codesandbox.io/s/interesting-buck-omruo8

Arman Ebrahimi
  • 2,035
  • 2
  • 7
  • 20

1 Answers1

4

StrictMode renders components twice in order to detect any problems with your code during development. You should be fine in production. If you absolutely don't want the double render then just remove the tag.

Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic.

Note: This only applies to development mode. Lifecycles will not be double-invoked in production mode.

React Docs: Strict Mode

Rakib Uddin
  • 880
  • 1
  • 6
  • 17
  • Thanks, Rakib. But my question is this `"two renders" is a warning about what thing`? And `And is there a way for rid of that(twice running) without removing Strict Mode from the app?` – Arman Ebrahimi Jun 05 '22 at 14:37
  • 1
    StrictMode renders life-cycle methods twice to ensure these checks. ```1. Identifying unsafe lifecycles. 2. Warning about legacy string ref API usage. 3. Warning about deprecated findDOMNode usage. 4. Detecting unexpected side effects.``` There are more. Please check the documentation for details. – Rakib Uddin Jun 06 '22 at 04:35