简体   繁体   中英

understanding react-hooks/exhaustive-deps useEffect and dispatching events

I have this warning:

React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

with this code:

import { useDispatch } from 'react-redux';
import openSocket from "socket.io-client";
import {populateCustomers} from './slices/CustomerSlice';
const ENDPOINT = config.ENDPOINT; //socket address

function App() {
  const dispatch = useDispatch();
  useEffect(() => {
    const socket = openSocket(ENDPOINT);
    //hydrate
    socket.on("hydrateCustomers",data=>dispatch(populateCustomers(data)))

  },[]);

the idea is that a socket is opened once, and on server events - data is dispatched from the response into the redux store.

I'm pretty sure I want an empty dependency array, as I only want this to run once... Is there a better way to handle this situation? or should I ignore this warning?

The useDispatch reference is stable , so you can add it to the dependency array without issue, it'll still only run on mount:

The dispatch function reference will be stable as long as the same store instance is being passed to the. Normally, that store instance never changes in an application.

However, the React hooks lint rules do not know that dispatch should be stable, and will warn that the dispatch variable should be added to dependency arrays for useEffect and useCallback. The simplest solution is to do just that:

 export const Todos() = () => { const dispatch = useDispatch(); useEffect(() => { dispatch(fetchTodos()) // Safe to add dispatch to the dependencies array }, [dispatch]) }

So you can safely change },[]); to },[dispatch]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM