Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why console.log inside the useEffect runs twice [duplicate]

i'm currently working with react project, which gets data from api and show it on the console.

although i wrote the console.log() just one time inside the useEffect hooks (with the [articles] dependency ), the web browser's console.log always shows the console.log two times like this: enter image description here

but i don't know reason why..

in my thought when the 'articles' state set by first useEffect hook, the second useEffect hook activates and console.log should be run only one time.. but it didn't.

here is my code

const NewsList = () => {

  const [articles, setArticles] = useState([]);

  useEffect(()=> {
    const getData = async () => {
      const response = await axios.get(`https://newsapi.org/v2/top-headlines?country=kr&apiKey=''
      `);
      setArticles(response.data.articles); 
    }
    getData();
  },[])

  useEffect(()=> {
    console.log(articles);
  },[articles])
  
  
  return (
    <div className="newsListBlock">
      <NewsArticle article={article}></NewsArticle>
      <NewsArticle article={article}></NewsArticle>
      <NewsArticle article={article}></NewsArticle>
      <NewsArticle article={article}></NewsArticle>
      <NewsArticle article={article}></NewsArticle>

    </div>
  );
};
like image 927
Stab-the-cake Avatar asked Oct 18 '25 15:10

Stab-the-cake


1 Answers

The effect is run every time the dependencies change.

  1. The first value, on the first update of the component, is [] (the initial state).
  2. The second value, after the data-getting effect runs, is whatever you get from newsapi.org.

Additionally, if you're using <StrictMode> and a React development build, certain lifecycles can be invoked twice. See e.g. this codesandbox; if you remove the <StrictMode> from index.js, you'll see less console.logs.

like image 94
AKX Avatar answered Oct 21 '25 04:10

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!