I'm working on a function that manages a string array based on object keys. Let's say it looks like this:
import React, { useState, useEffect } from "react";
import FieldContext from "../contexts/FieldContext";
import io from "socket.io-client";
const [socket, setSocket] = useState(null);
// the `data` array gets changed every second due to a WebSocket, in case that's important
const [data, setData] = useState({ foo: [], bar: [] });
const [connections, setConnections] = useState(["conn1", "conn2"]);
const { checkedFields } = useContext(FieldContext); // ["foo", "moo"];
useEffect(() => {
setConnections(prevConnections => {
// The code below does the following:
// Loop through the temporary connections (which is a copy of checkedFields)
// A. if `tempConn` is a key in the `data` object, push the name with `update_` prefix to the `_conns` array
// B. If not, just push it without a prefix to the `_conns` array
// Since the `checkedFields` array is ["foo", "moo"], the first element will get the prefix,
// the other won't and will just get pushed.
let _tempConns = [...checkedFields];
let _conns = [];
_tempConns.forEach(tempConn => {
if (data[tempConn] !== undefined) _conns.push(`update_${tempConn}`);
else _conns.push(tempConn);
});
return _conns;
});
}, [checkedFields]);
// the websocket hook
useEffect(() => {
const _socket = io(WS_URI);
_socket.on("info", data => {
// some magic happens here to add to the `data` object which is not important for this question
});
setSocket(_socket);
}, [])
I get the following warning while using this hook: React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array
. Which I understand, but if I include data
in the dependency array, I get an enormous amount of unnecessary updates. How do I prevent that from happening? (without using // eslint-disable-next-line
please)