React Component Re-execute incorrectly

Viewed 27

In my simple react app there two component: App and Comments.

App.js =>

import Comments from "./comments/Comments";

const App = () => {
    return (
        <div>
            <h1>App.js</h1>
            <Comments currentUserId="1" />
        </div>
    );
};

export default App;

Comments.js =>

import { useState, useEffect } from "react";
import { getComments as getCommentsApi } from "../api";

const Comments = ({ currentUserId }) => {
    const [comments, setComments] = useState([]);
    console.log("Comments", comments);
    
    useEffect(() => {
        getCommentsApi()
        .then(data => {
            setComments(data);
        })
    }, []);
    
    return (
        <div>
            <h1>Comments.js</h1>
        </div>
    );
};

export default Comments;

If you take a look at my Comments Component, there im logging the Comments in the function body and it should be execute two time, first for the initial load and the second time due to the useEffect and changing the state.

React Components Should Re-execute when props or state changed

But 4 logs appear in my console. Why?

enter image description here

1 Answers

I think you are using strict Mode, that's why you are getting the unexpected result. Remove the Strict Mode component from the index.js file and the code will work as expected

Related