React Hook 중에 가장 유명한(?) 두개의 Hook이라고하면 나는 useEffect와 useState를 먼저 떠올린다.
useEffect는 외부 시스템으로과 컴포넌트를 동기화(synchronize a component with an external system)하는 리액트 훅이라고 공식문서에서 설명하고 있다.
외부 시스템과 컴포넌트를 동기화 한다는 말이 무슨 뜻일까?
다시 공식 문서를 보면
For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. Effects
let you run some code after rendering so that you can synchronize your component with some system outside of React.
리액트 state(상태)에 따른 비리액트 컴포넌트를 제어하거나 서버 연결을 설정하거나 컴포넌트가 스크린에 나타났을 때 분석 로그를 보낼 수 있다. Effect는 렌더링 후 일부 코드를 실행하여 React 외부 시스템과 컴포넌트를 동기화할 수 있다.
이렇게 설명되어 있는데, 여전히 이해하기 어렵다.
기본 구조부터 보면
useEffect(setup, dependencies?)
setup은 콜백함수이고, dependencies는 optional인데 배열 형태로 들어간다.
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.
앞서 언급한 Effect의 로직이다. optional하게 클린업 함수를 반환하게 할 수 있다. 컴포넌트가 DOM에 추가될 때 React는 이 함수를 실행한다. dependencies 안에 넣은 값이 바뀔때마다 리액트는 클린업 함수를 작동시키며 새로운 값을 할당한다. 컴포넌트가 DOM에서 제거될 때 React는 클린업 함수를 작동하게 한다.
다시 말해서, 최초 렌더링 시, 의존성 배열안에 있는 값이 바뀔 때, 클린업 함수를 추가 했다면 컴포넌트가 언마운트(제거)될 때 setup이라는 콜백함수가 작동한다. 단, 컴포넌트가 제거될 때에는 클린업 함수가 작동하고 나서 클린업 함수를 제외한 셋업 함수가 작동한다.
가령
이러한 코드가 있다고 가정할 때,
이 컴포넌트가 최초로 렌더링될 때 createConnection으로 커넥션을 생성해서 변수에 할당하고, 이를 커넥트 하는 과정이 일어난다.
의존성 배열에 있는 roomId가 바뀌게 되면 이전에 렌더링 되었던 컴포넌트는 클린업 함수에 의해 disconnect가 호출되고, 최초 렌더링 시 발생한 connect 함수가 호출된다.
'기술스택 > React.js' 카테고리의 다른 글
[React 19] useReducer (0) | 2025.04.27 |
---|---|
[React 19] useMemo (0) | 2025.03.30 |
[React 19] useContext (0) | 2025.03.25 |
[React 19] useCallback (0) | 2025.03.23 |
[React 19] useActionState (1) | 2025.03.22 |