Just by instantiating the following code in another components
import React, { useState, useCallback, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const WebsocketHandler = () => {
const { lastJsonMessage, readyState } = useWebSocket('ws://127.0.0.1:8001/ws', {
shouldReconnect: (closeEvent) => {
return true;
},
reconnectAttempts: 99999,
reconnectInterval: 5000
});
const [isResponsive, setIsResponive] = useState(true);
useEffect(() => {
console.log("lastJsonMessage: " + JSON.stringify(lastJsonMessage));
}, [lastJsonMessage])
useEffect(() => {
console.log("readyState: " + readyState);
}, [readyState])
return isResponsive;
};
I got rerenders or to be more precise, i got some console output from my other components, so it looks like stuff is rerendered on every receive. I don't use the return value, so whats going on here? How can I avoid that? Edit: The console log in this compoment is not the issue. The output will also come from other compoments in the application.
useEffect will run everytime lastJsonMessage or readyState value change. useEffect is a react hook and will run after side effects based parameters. For more info Using the Effect Hook
Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before.
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
If you don't want to logging delete the both useEffects. if you want console log once
useEffect(() => {
console.log("lastJsonMessage: " + JSON.stringify(lastJsonMessage));
console.log("readyState: " + readyState);
}, [])
but this code may want to change based your want