useEffect dependency with Context API. My code works fine with empty array but still gives the warning

Viewed 275

So. I get clients from context as initialState and the code below is from my listing component (listClients.js or smth) . I update the context with the data fetched from firebase. Everything works fine actully with using empty array as dependency. I get my final array listed on my list component.. But eslint is still saying me that I should add "clientsRef" and "updateClients" into dependency but this causes an infinite loop. So what should I do with that? Close my eyes to this warning?

const { clients, removeClient, updateClients } = useContext(ClientsContext);
const collection = 'clients';
const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');


useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);     

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);
1 Answers

You can declare the clientsRef within the useEffect and for updateCloients function you can make use of useCallback in the ContextProvider. Once you do that you can add them as a dependency to useEffect

const { clients, removeClient, updateClients } = useContext(ClientsContext);



useEffect(() => {
    const collection = 'clients';
     const clientsRef = firestore.collection('clients').orderBy('createdAt', 'desc');
    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);     

    });

    return () => {
        unsubscribeFromSnapshot();
    }
}, []);

In ClientContext Provider

const updateClients = useCallback(() => {
   // logic here
}, []);

However if you are sure that you just want the logic within useEffect to run once and not anytime later, you can disable the warning with

// eslint-disable-next-line react-hooks/exhaustive-deps

Ex:

useEffect(() => {

    const unsubscribeFromSnapshot = clientsRef.onSnapshot(async snapshot => {
        const clientsMap = convertSnapshotToMap(snapshot);
        updateClients(clientsMap);     

    });

    return () => {
        unsubscribeFromSnapshot();
    }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

For more details please check this post:

How to fix missing dependency warning when using useEffect React Hook?

Related