why console.log inside the useEffect runs twice

Viewed 60

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

2 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.

From the official react doc:

By using this Hook, you tell React that your component needs to do something after render.

So this useEffect will run once on the first render of the component, and then run a second time due to the use the setArticles function which update articles.

Related