본문 바로가기
React

[리액트] 컴포넌트 렌더링시 useEffect 한번만 실행되도록 바꿔주기

by 메이플 🍁 2022. 8. 23.

리액트에서 컴포넌트가 렌더링되면 useEffect가 두번 실행된다. 이는 개발 단계에서 디버깅하기 편하라고 만들어준 자체 기능이기 때문에 엔드 프로덕트에서는 필요 하지 않고 개발시에만 사용된다.

 

index.js

index.js에 있는 <React.StrictMode> 태그는 리액트에서 컴포넌트가 마운트 될때 useEffect 함수를 2번 실행시킨다. 해당 태그는 리액트 전체에 디버깅을 위한 절차를 추가해주는 태그로, useEffect 의 이상동작을 감지하고자 2번 실행시키도록 설정되어져 있다.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

index.js

useEffect 요청을 한번만 보내고 싶다면 index.js 파일에 React.StrictMode 컴포넌트를 제거해주면 된다.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <App />
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

댓글