state를 의존성 배열에 넣어준다.
const [count, setCount] = useState(0);
useEffect(() => {
if (count > 10) return;
setCount(count + 1);
}, [count]);
useeffect안에 함수 정의가 들어가는 경우 함수 실행시 필요한 변수를 넣어준다.
const getInitNoti = async () => {
const res = await apis.notification.getNotice(params);
setNotiData(res.data.user_notices);
};
useEffect(() => {
getInitNoti();
}, [getInitNoti]);
함수 실행에 필요한 params 변수를 의존성 배열에 추가해준다
const getInitNoti = async () => {
const res = await apis.notification.getNotice(params);
setNotiData(res.data.user_notices);
};
useEffect(() => {
getInitNoti();
}, [getInitNoti, params]);
useCallback안에 함수 정의를 넣는다
const getInitNoti = useCallback(async () => {
const res = await apis.notification.getNotice(params);
setNotiData(res.data.user_notices);
}, [params]);
useEffect(() => {
getInitNoti();
}, [getInitNoti]);
useCallback이 없다면 위 컴포넌트가 리렌더링 될때마다, 계속해서 getInitNoti함수를 만들게 되고, 새로운 참조값을 받기 때문에 getInitNoti함수를 실행하게 됩니다.
하지만 useCallback을 정의 하면 params가 바뀔때 만 getInitNoti가 실행되어, 불필요한 함수 생성 및 실행을 막을 수 있습니다.