React로 개발을 하며 여러가지 오류상황을 만나게 됩니다..그중 가장 최근에 만난 오류 해결에 대해 기록하려고 합니다 😇 😇 😇
아래의 오류는 useEffect내에 사용하고 있는 state를 배열안에 추가시켜 달라는 의미입니다!
React Hook useEffect has a missing dependency: 'xxxxx'. Either include it or remove the dependency array.
const [count, setCount] = useState(0);
useEffect(() => {
if (count > 10) return;
setCount(count + 1);
}, [count]);
------------------------------------------------------------------------------------
const [count, setCount] = useState(0);
useEffect(() => {
if (count > 10) return;
// state = 0
setCount(state => state + 1);
}, []);
const getInitNoti = async () => {
const res = await apis.notification.getNotice(params);
setNotiData(res.data.user_notices);
};
useEffect(() => {
getInitNoti();
}, [getInitNoti]);
getInitNoti
함수가 params
라는 변수를 쓰기 때문에 이 값을 배열에 넣어줘야 경고가 나오지 않습니다.const getInitNoti = async () => {
const res = await apis.notification.getNotice(params);
setNotiData(res.data.user_notices);
};
useEffect(() => {
getInitNoti();
}, [getInitNoti, params]);
const getInitNoti = useCallback(async () => {
const res = await apis.notification.getNotice(params);
setNotiData(res.data.user_notices);
}, [params]);
useEffect(() => {
getInitNoti();
}, [getInitNoti]);
getInitNoti
함수를 만들게 되고, 새로운 참조값을 받기 때문에 getInitNoti
함수를 실행하게 됩니다.params
가 바뀔때 만 getInitNoti
가 실행되어, 불필요한 함수 생성 및 실행을 막을 수 있습니다.