Skip to content
Advertisement

why console.log inside the useEffect runs twice

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>
  );
};

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement