프론트엔드/리액트
useEffect에 대하여
도툐리
2024. 3. 13. 02:59
useEffect(setup, dependencies?)
- 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.
- dependencies: 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. If you specify the dependencies, your Effect runs after the initial render and after re-renders with changed dependencies.
그럼 만약 React에서 useEffect를 사용할 때, 컴포넌트가 처음 렌더링될 때 특정 작업을 수행하지 않고, 특정 값이 변경될 때만 작업을 수행하게 하려면? -> 보통 useRef를 사용하여 이전 값이나 첫 렌더링 여부를 추적함.
(ex)
import { useEffect, useRef, useState } from 'react';
function MyComponent() {
const [value, setValue] = useState(''); // 이것이 변경될 때마다 어떤 작업을 하고 싶은 상태입니다.
const isInitialMount = useRef(true); // 컴포넌트가 처음 마운트되었는지 확인하기 위한 ref
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false; // 첫 마운트에서는 아무 작업도 수행하지 않고, 이후의 마운트에서만 작업을 수행합니다.
} else {
// value가 변경될 때마다 실행하고 싶은 작업을 여기에 배치합니다.
console.log(`Value has changed to: ${value}`);
}
}, [value]); // 의존성 배열에 value를 넣어서 value가 변경될 때만 useEffect가 실행되도록 합니다.
return (
<div>
<input value={value} onChange={e => setValue(e.target.value)} />
</div>
);
}
참고자료
https://react.dev/reference/react/useEffect#my-effect-runs-twice-when-the-component-mounts
useEffect – React
The library for web and native user interfaces
react.dev