If your effect returns a function, React will run it when it is time to clean up:
useEffect(() => {
chart.current = createChart('chart-container', {
width: 960,
height: 500,
crosshair: {
mode: CrosshairMode.Normal,
}
});
return function () {
chart.current?.remove();
}
}, []);
References: