본문 바로가기
프로그래밍/React

[React] useEffect

by YuminK 2023. 11. 28.

useEffect

useEffect is a React Hook that lets you synchronize a component with an external system.

 

useEffect(setup, dependencies?)

 

예시)

  useEffect(() => {

    const connection = createConnection(serverUrl, roomId);

    connection.connect();

    return () => {

      connection.disconnect();

    };

  }, [serverUrl, roomId]);

 

Parameters 

setup: The function with your Effect’s logic. Your setup function may also optionally return a cleanup function. When your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function.

 

돔에 들어갔을 때 처음 실행되고 의존성이 변경되면 re-render 이후에 처리된다. return 값으로 cleanup 함수가 제공될 수 있다. 돔에서 컴포넌트가 사라졌을 때도 cleanup 함수는 호출된다.

 

optional dependencies: The list of all reactive values referenced inside of the setup code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is configured for React, it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like [dep1, dep2, dep3]. React will compare each dependency with its previous value using the Object.is comparison. If you omit this argument, your Effect will re-run after every re-render of the component

 

의존성으로 준 값이 변하는 경우, 컴포넌트의 re-render 후에 처리가 된다. 컴포넌트 상단에서 써라. 의존성을 제대로 줘라. 렌더링 이후에 호출된다는 것을 인지하고 시각적 처리를 원하는 경우 useLayoutEffect를 사용하라.

 

function ChatRoom({ roomId }) { // This is a reactive value

 const [serverUrl, setServerUrl] = useState('https://localhost:1234'); // This is a reactive value too

 

 useEffect(() => {

   const connection = createConnection(serverUrl, roomId); // This Effect reads these reactive values

   connection.connect();

   return () => connection.disconnect();

 }, [serverUrl, roomId]); // ✅ So you must specify them as dependencies of your Effect

 // ...

}

 

반응적인 값들이 의존성으로 설정되어야 한다. 만약 의존성이 존재하지 않는다면 컴포넌트 props나 상태 변경에 다시 실행되지 않는다. 

 

useEffect는 초기 렌더 이후와 의존성 변경(render 이후)에 처리된다. 의존성이 있을 때는 초기에만 처리되고 변경되지 않는다. 의존성이 있는 경우 초기에, 변경될 때 처리한다. 아예 빈 배열도 넣지 않으면 매번 처리된다. (사용하지 말것)

 

빈 배열의 의존성으로 초기 셋팅을 위해 사용할 수 있다. 

 

const serverUrl = 'https://localhost:1234';

 

function ChatRoom({ roomId }) {

 const [message, setMessage] = useState('');

 

 const options = { // 🚩 This object is created from scratch on every re-render

   serverUrl: serverUrl,

   roomId: roomId

 };

 

 useEffect(() => {

   const connection = createConnection(options); // It's used inside the Effect

   connection.connect();

   return () => connection.disconnect();

 }, [options]); // 🚩 As a result, these dependencies are always different on a re-render

 // ...

 

이런 코드는 매번 객체를 재생성하므로 의존성으로 넣기에 부적합하다. 차리라 useEffect 내에 객체를 넣으라고 한다. 

 

function ChatRoom({ roomId }) {

 const [message, setMessage] = useState('');

 

 function createOptions() { // 🚩 This function is created from scratch on every re-render

   return {

     serverUrl: serverUrl,

     roomId: roomId

   };

 }

 

 useEffect(() => {

   const options = createOptions(); // It's used inside the Effect

   const connection = createConnection();

   connection.connect();

   return () => connection.disconnect();

 }, [createOptions]); // 🚩 As a result, these dependencies are always different on a re-render

 // ...

 

이 역시 매 렌더링 마다 함수가 재생성되므로 처리하지 말고 그냥 useEffect에 넣어야 한다. 

 

https://react.dev/reference/react/useEffect

'프로그래밍 > React' 카테고리의 다른 글

[React] useCallback  (1) 2023.11.28
[React] useRef  (0) 2023.11.28
[React] useState  (0) 2023.11.27
[React] 리액트 개요  (0) 2023.11.27
[React] 이미지 업로드 및 미리보기  (0) 2023.09.09

댓글