0
Follow
4
View

Code making a lot of unnecessary Firestore Read Operations

csfxxaq 注册会员
2023-01-26 05:43

Without seeing what or how this Home component is rendered or anything else your app may be doing with your firestore, it seems likely that since postsCollectionRef is a new reference any time this Home component renders that this is triggering the useEffect hook callback also on each render.

If nothing else references postsCollectionRef then move it either outside the component into the useEffect's callback scope so it can be removed as an external dependency. This allows you to use an empty dependency so the useEffect hook callback is called only once when the Home component mounts.

const [postList, setPostList] = useState([]);

useEffect(() => {
  const postsCollectionRef = collection(db, "Posts");

  const getPosts = async () => {
    const data = await getDocs(postsCollectionRef);
    setPostList(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
  }

  getPosts();
}, []);

If on the other hand postsCollectionRef referenced elsewhere, then again, either move it outside the component or memoize it's value so it's a stable reference from render to render.

const [postList, setPostList] = useState([]);
const postsCollectionRef = useRef(collection(db, "Posts"));

useEffect(() => {
  const getPosts = async () => {
    const data = await getDocs(postsCollectionRef.current);
    setPostList(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
  }

  getPosts();
}, []);

// use postsCollectionRef.current elsewhere for accesses

About the Author

Question Info

Publish Time
2023-01-26 05:43
Update Time
2023-01-26 05:43

Related Question