Home > database >  Why getting too many rerenders in react?
Why getting too many rerenders in react?

Time:05-11

I have the following code in React to get data from Firebase. I am new to useEffect and it is giving too many rerenders error:

let post1 = [];
useEffect(() => {
  getDocs(collection(db, "posts")).then((snapshot) => {
    const data = snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data(),
    }));
    post1 = data;
  })
}, [posts]);
setPosts(post1);

CodePudding user response:

The way you wrote it, setPosts(post1) is being called on every render. I'm assuming posts and setPosts are destructured from a useState() value which means that every time you call setPosts(), it triggers a rerender. You need to move the setPosts() call to the useEffect(). You also need to remove posts from the dependency array of useEffect because if any of those dependencies change, it triggers a rerender as well. In your specific case, try this:

useEffect(() => {
  getDocs(collection(db, "posts")).then((snapshot) => {
    const data = snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data(),
    }));
    setPosts(data);
  })
}, []);
  • Related