I am creating a chat app in React using socket.io. I don't need the following useEffect() to run more than once, and what this warning message is asking me to resolve would conflict with my intention of setting the socket message handler only once:
React Hook useEffect has a missing dependency: 'messages'. Either include it or remove the dependency array. You can also do a functional update 'handleMessages(m => ...)' if you only need 'messages' in the 'handleMessages' call.eslintreact-hooks/exhaustive-deps
export default function Group(props) {
const [_broadcastOptions, handleBroadcastOptions] = useState(false);
const [messages, handleMessages] = useState([]);
const textValue = useRef('');
const bottomScrollRef = useRef();
const socket = useRef();
useEffect(()=>{
console.log('bruh');
socket.current = io('http://0.0.0.0:3001');
socket.current.on('connect', ()=> {
console.log('socket connection status: ' + socket.current.connected);
socket.current.emit('enter-room', getRoomId(window.location.pathname));
});
socket.current.on('message', m => {
console.log('message received: ' + JSON.stringify(m));
handleMessages([...messages, m]);
});
}, []);
return (...);
}
Edit: I've tried passing in a callback in my handleMessages function (functional updates as react calls them) but I still get the warning.
[![enter image description here][2]][2]
If you use the callback for handleMessages
instead, there's no need to use the outer messages
identifier (which would be in an old closure anyway).
socket.current.on('message', m => {
console.log('message received: ' + JSON.stringify(m));
handleMessages(messages => [...messages, m]);
});