When the data that comes from the WebSocket changes, the component with the graph is redrawn and flashes. I sort through the data using map()
and display it in a table. Also in useEffect
I update and create an array of data for the chart.
What can be done to stop the blinking?
Component code
export const TablePanel = () => {
const wsResponseData = useContext(WsDataContext)
const httpResponseData = useContext(HttpDataContext)
const [chartData, setChartData] = useState<CoordsType[]>(initialLineChartData)
useEffect(() => {
if (httpResponseData.length > 0) {
httpResponseData.forEach(httpData => {
wsResponseData[httpData.Names[0]].slice(-1).forEach((data) => {
if (data.cpu_stats.online_cpus) {
setChartData(prevState => [
...prevState,
{x: getCurrentTime(), y: cpuUsage(data)}
].slice(-20))
}
})
})
}
}, [httpResponseData, wsResponseData])
const memoizedChartData = useMemo(() => chartData, [chartData]);
return (
<Table>
<thead>
<tr>
{ headTableData.map(headName => (
<th key={headName}>{headName}</th>
))}
</tr>
</thead>
<tbody>
{ httpResponseData.map(httpData => (
wsResponseData[httpData.Names[0]].slice(-1).map((data) => (
<tr key={data.keyId}>
<td>{httpData.Names[0]}</td>
<td>{data.pids_stats.current ?? "null"}</td>
<td>
<span title={httpData.Image}>{httpData.Image}</span>
</td>
<td>{ data.cpu_stats.online_cpus ?
<div style={{ height: "46px", width: "140px"}}>
<LineChartWithoutLegend chartData={memoizedChartData} />
</div> :
"null"}
</td>
<MemoryCell data={data} />
</tr>
))
))}
</tbody>
</Table>
)
}
Component with chart
export const LineChartWithoutLegend = ({ chartData }: { chartData: CoordsType[] }) => {
return (
<ResponsiveLine
data={[
{
id: "CPU usage monitoring",
data: chartData,
},
]}
margin={{ top: 5, right: 0, bottom: 14, left: 0 }}
xScale={{ type: 'point' }}
yScale={{
type: 'linear',
min: 0,
max: 100,
stacked: false,
reverse: false
}}
axisTop={null}
axisRight={null}
axisBottom={null}
axisLeft={null}
lineWidth={1}
colors="#000000"
enableGridX={false}
enableGridY={false}
enablePoints={false}
isInteractive={false}
enableCrosshair={false}
legends={[]}
animate={false}
motionConfig="default"
/>
)
}
I tried using memoization to reduce the rendering of the graph component, but it doesn’t work
New contributor
mmorrii is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.