[TIL] 내배캠4기-NextJs-127일차

hare·2023년 3월 7일
0

내배캠-TIL

목록 보기
72/75

Error: Maximum update depth exceeded..

커스텀훅을 만들며 useEffect 의존성배열을 state값이 업데이트 될때마다 렌더링되도록 코드를 짜놨었다. 이 커스텀훅을 부르는 컴포넌트에서도 역시 useEffect를 사용했는데, Maximum update depth exceeded 에러를 뱉어내는 것이다.

문제가 된 커스텀훅

  useEffect(() => {
    const getCommunityPost = () => {
      const communityRef = collection(dbService, "communityPost");
      const q = query(communityRef, orderBy("writtenDate", "desc"));
      onSnapshot(q, (snapshot) => {
        const newPosts = snapshot.docs.map((d) => {
          const newPost = {
            id: d.id,
            writterUid: d.data().uid,
            category: d.data().category,
            title: d.data().title,
            editorText: d.data().editorText,
            writtenDate: convertTimestamp(d.data().writtenDate),
            thumbnail: d.data().thumbnail,
          };
          return newPost;
        });
        setCommunityPost(newPosts);
      });
    };
    getCommunityPost();
  }, [communityPost]); //📌 여기서 이미 위의 에러를 뱉을 수 밖에 없는 것 같다.

커스텀훅 호출 컴포넌트

  const { communityPost } = useGetCommunityPost();
  useEffect(() => {
    setCommunityList(communityPost);
  }, [communityPost]); 

여기서 의존성배열을 넣고 커스텀훅에서는 빈배열로 변경하니 에러가 뜨지 않았다.
호출 컴포넌트도 빈배열로 주면 첫 렌더링 시 데이터가 바로 뜨지 않거나 새로고침이 필요했다.

생각해보면 무한렌더링 되는게 당연하게도 보인다. 코드를 짤때는 깊이 생각하지 못했는데, 에러메세지가 자세해서 금방 해결할 수 있었다.

profile
해뜰날

0개의 댓글