πŸ“React Hook useEffect has a missing dependency 경고문에 λŒ€ν•œ κ³ μ°°

10_2pangΒ·2023λ…„ 6μ›” 5일
0

βš½οΈνŠΈλŸ¬λΈ”μŠˆνŒ…

λͺ©λ‘ 보기
40/94
post-thumbnail

πŸ‘¨β€πŸ’»Β μ‚¬κ±΄


  • νŒ€ν”„λ‘œμ νŠΈ 쀑 기본적인 κΈ°λŠ₯ κ΅¬ν˜„μ„ 마친 ν›„, node 창을 μ‚΄νŽ΄λ³΄λ‹ˆ 같은 λ‚΄μš©μ˜ warning 문ꡬ가 λ°œμƒν•˜λŠ” 것을 λ³Ό 수 μžˆμ—ˆλ‹€. (**React Hook useEffect has a missing dependency)** 이λ₯Ό ν•΄κ²°ν•˜κ³ μž, μ—¬λŸ¬ 방면으둜 μ°Ύμ•„ λ³΄μ•˜λ‹€.

βœ…Β ν•΄κ²°


일단, κ°„λž΅ν•˜κ²Œ λ§ν•˜μžλ©΄ useEffect μ—μ„œ μ‹€ν–‰λœ ν•¨μˆ˜μ˜ λ³€μˆ˜κ°’μ„ useEffect μ˜μ‘΄μ„±λ°°μ—΄μ— 섀정을 μ•ˆν•΄μ£Όμ–΄μ„œ 생긴 λ¬Έμ œμ΄λ‹€.
이λ₯Ό ν•΄κ²°ν•˜κΈ° μœ„ν•œ 방법이 두가지 μ‘΄μž¬ν•œλ‹€.

  1. useEffect μ•ˆμ— ν•¨μˆ˜λ₯Ό μ„ μ–Έν•΄μ£Όκ³ , κ·Έ ν•¨μˆ˜μ— λ°œμƒν•œ λ³€μˆ˜κ°’μ„ useEffect μ˜μ‘΄μ„± λ°°μ—΄μ•ˆμ— 섀정해두기

    useEffect(() => {
    	const getChatroomData = () => {
      axios({
        url: `https://mandarin.api.weniv.co.kr/post/${chatRoomId}`,
        method: 'get',
        headers: {
          Authorization: `Bearer ${userToken}`,
          'Content-type': 'application/json',
        },
      })
        .then((response) => {
          setChatRoomData(response.data.post);
        })
        .catch((error) => {
          console.log(error);
        });
    	};
    	if(chatRoomId&&userToken){
    	  getChatroomData();
    	}
    }, [chatRoomId,userToken]);
  2. 주석을 톡해 μ˜ˆμ™Έμ²˜λ¦¬ν•˜κΈ° ( 근본적인 해결방법은 μ•„λ‹˜ )

    β†’ κ·ΈλŸΌμ—λ„ μ‚¬μš©ν•˜λŠ” 이유 : μž¬μ‚¬μš©λ„ ν•΄μ•Όν•˜κ³ , λ³€μˆ˜κ°€ μ—†λŠ” ν•¨μˆ˜λ₯Ό useEffectλ₯Ό 톡해 λ Œλ”λ₯Ό ν•΄μ•Όν•  κ²½μš°μ—λŠ” μ–΄μ©” 수 없이 μ£Όμ„μ²˜λ¦¬λ₯Ό ν•˜μ—¬ μ‚¬μš©ν•œλ‹€.

    const getChatroomData = () => {
      axios({
        url: `https://mandarin.api.weniv.co.kr/post/${chatRoomId}`,
        method: 'get',
        headers: {
          Authorization: `Bearer ${userToken}`,
          'Content-type': 'application/json',
        },
      })
        .then((response) => {
          setChatRoomData(response.data.post);
        })
        .catch((error) => {
          console.log(error);
        });
    };
    useEffect(() => {
      if(chatRoomId&&userToken){
    	  getChatroomData();
    	}
    	// μ•„λž˜μ™€ 같은 μ£Όμ„μ²˜λ¦¬λ₯Ό 톡해, eslint warning이 λ°œμƒν•˜μ§€ μ•Šλ„λ‘ μ„€μ •ν•œλ‹€.
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [chatRoomId,userToken]);

πŸ’­Β κ°œμ„ 


νŒ€ ν”„λ‘œμ νŠΈ 쀑, 1의 λ°©μ•ˆμ„ 택할 수 μžˆμŒμ—λ„ 2λ₯Ό μ“΄ κ²½μš°λŠ” λ¦¬νŒ©ν† λ§ 과정을 κ±°μΉ  μ˜ˆμ •μ΄λ‹€.

profile
μ£Όλ‹ˆμ–΄ ν”„λ‘ νŠΈμ—”λ“œ 개발자 이광렬 μž…λ‹ˆλ‹€ 🌸

0개의 λŒ“κΈ€