Solve the issue of React displaying old data on hovering Chart.js

If you are using Chart.js in React, and the graph is displaying old data on hover, remember to destroy the chart when unsubscribing on useEffect:

jsx
import React, { useEffect, useState } from 'react';

const Graph = () => {
    
    const [clicks, setClicks] = useState(0);
    
    useEffect(() => {
        
        // Dummy function to fetch data
        let graph  = fetchData();
        
        // Creating the graph
        let canvas = document.getElementById('graph');
        let ctx    = canvas.getContext('2d');
        let chart  = new Chart(ctx, graph);
        
        // If you don't destroy the chart, you'll generate 
        // a new graph on each click
        return () => chart.destroy();
        
    }, [clicks]);
    
    return(
        <>
            <canvas id = 'graph'></canvas>
            <button onClick = {() => setClicks(clicks + 1)}>Click me</button>
        </>
    );
    
}

export default Graph;

If you have a listener and useEffect doesn't have arguments, you can use the update() function:

jsx
import React, { useEffect, useState } from 'react';

const Graph = () => {
    
    const [clicks, setClicks] = useState(0);
    
    useEffect(() => {
        
        // Defining graph
        let graph;
        
        // Creating the graph
        let canvas = document.getElementById('graph');
        let ctx    = canvas.getContext('2d');
        let chart  = new Chart(ctx, graph);
        
        // Setting active listening
        someListenerToGetData.on('value' => {
            
            // Getting data from the listener
            graph = getData();
            
            // Updating the data when the listener
            // detects new data
            chart.update();
            
        });
        
    }, []);
    
    return(
        <>
            <canvas id = 'graph'></canvas>
            <button onClick = {() => setClicks(clicks + 1)}>Click me</button>
        </>
    );
    
}

export default Graph;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.