1

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 Answer 1

2

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

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

2 Comments

Np, glad to help @MORA
@MORA you should flag his comment as answer :)

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.