1

I'm using ReactJS and Google FireStore to create a simple stock portfolio tracking app. How can I access database functions from within useEffect without triggering the warning "React Hook has a missing dependency"? I've tried playing around a bit with useCallback, but no success so far. Or is it ok to ignore these warnings?

var db = firebase.firestore();
  useEffect(() => {
    //get user's cost averages from db

    if (props.userStatus) {
      db.collection("users")
        .doc(props.userStatus)
        .get()
        .then((doc) => {
          if (doc.exists) {
            if (doc.data().portfolio) {
              setCostAverages(doc.data().portfolio);
            }
          }
        });
    }
  }, [props.userStatus]);

Warning msg: "React Hook useEffect has missing dependency 'db'

1
  • 1
    Can you share your package.json ? Commented Oct 23, 2021 at 14:47

1 Answer 1

0

The frequent solution to this warning is to add the reference of the Firestore instance to the dependency array of the useEffect() hook function. You can check this related thread and Github issue for more details. For your code snippet, the dependency array would need to look like this:

var db = firebase.firestore();
  useEffect(() => {
    //get user's cost averages from db
    //...
  }, [props.userStatus, db]);

According to the documentation, the dependency array should include all values used in the effect scope:

If you use this optimization, make sure the array includes all values from the component scope (such as props and state) that change over time and that are used by the effect. Otherwise, your code will reference stale values from previous renders.

Finally, I found a detailed guide which goes much in depth into this dependency array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.