Is it a good practice to use React useEffect as listener to trigger action?

Viewed 30

I have a ProgressBar component to get the progress I subscribe to two different events because the user uploads two different files. Each event returns the upload progress of each file and then I combine these two progress into a single one and display it to the user.

The question is: I have an useEffect that listen to these two other progress and when they're updated I update the "final" progress by summing the values or mutiplying by 2 if there is only a single source of progress (because the user can upload only one file). Is it okay to use useEffect like this?

Component code:

const ProgressBar = () => {
const [progressVideo, setProgressVideo] = useState(0);
const [progressData, setProgressData] = useState(0);
const [progress, setProgress] = useState(0);

useEffect(() => {
  window.electron.api.globals.ipcRenderer.on(
    "recorder:source1",
    (evt, message) => {
    console.log("message1 ", message.percent);
    setProgressVideo(message?.percent / 2);
  }
);
  window.electron.api.globals.ipcRenderer.on(
  "recorder:source2",
  (evt, message) => {
    console.log("message2 ", message.percent);
    setProgressData(message?.percent / 2);
  }
);
}, []);

useEffect(() => {
if (isNaN(progressVideo) && isNaN(progressData)) return;

const isSingleSourceVideo = isNaN(progressData);
if (isSingleSourceVideo) {
  setProgress(progressVideo * 2);
} else {
  setProgress(progressVideo + progressData);
}
}, [progressVideo, progressData]);

return (
  <div id={styles.progressBarWrapper}>
    <div id={styles.progressBarBackground}>
      <p>{parseInt(progress)}%</p>
    </div>
    <div
      id={styles.progressBar}
      style={{ width: parseInt(progress) + "%" }}
    ></div>
  </div>
 );
};
1 Answers

It's good as long as you do clean up and remove the listeners when they are done

useEffect(() => {
  
  function calculate(evt, message){
      console.log("Message", message.percent);
    setProgressVideo(message?.percent / 2);
  }

  window.electron.api.globals.ipcRenderer.on(
    "recorder:source1", calculate
);
  window.electron.api.globals.ipcRenderer.on(
  "recorder:source2", calculate
);

return () => {
  window.electron.api.globals.ipcRenderer.removeListener(
    "recorder:source1", calculate
);
  window.electron.api.globals.ipcRenderer.removeListener(
  "recorder:source2", calculate
);
}
}, []);

Related