Skip to content

Commit

Permalink
Add useCallback on hook methods (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
samhirtarif authored May 24, 2023
1 parent 79316e7 commit d2200d3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 12 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "react-audio-voice-recorder",
"private": false,
"version": "1.1.6",
"version": "1.1.7",
"license": "MIT",
"author": "",
"repository": {
Expand Down
31 changes: 22 additions & 9 deletions src/hooks/useAudioRecorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,17 @@ const useAudioRecorder: (
const [timerInterval, setTimerInterval] = useState<NodeJS.Timer>();
const [recordingBlob, setRecordingBlob] = useState<Blob>();

const _startTimer: () => void = () => {
const _startTimer: () => void = useCallback(() => {
const interval = setInterval(() => {
setRecordingTime((time) => time + 1);
}, 1000);
setTimerInterval(interval);
};
}, [setRecordingTime, setTimerInterval]);

const _stopTimer: () => void = () => {
const _stopTimer: () => void = useCallback(() => {
timerInterval != null && clearInterval(timerInterval);
setTimerInterval(undefined);
};
}, [timerInterval, setTimerInterval]);

/**
* Calling this method would result in the recording to start. Sets `isRecording` to true
Expand All @@ -86,23 +86,36 @@ const useAudioRecorder: (
console.log(err.name, err.message, err.cause);
onNotAllowedOrFound?.(err);
});
}, [timerInterval]);
}, [
timerInterval,
setIsRecording,
setMediaRecorder,
_startTimer,
setRecordingBlob,
onNotAllowedOrFound,
]);

/**
* Calling this method results in a recording in progress being stopped and the resulting audio being present in `recordingBlob`. Sets `isRecording` to false
*/
const stopRecording: () => void = () => {
const stopRecording: () => void = useCallback(() => {
mediaRecorder?.stop();
_stopTimer();
setRecordingTime(0);
setIsRecording(false);
setIsPaused(false);
};
}, [
mediaRecorder,
setRecordingTime,
setIsRecording,
setIsPaused,
_stopTimer,
]);

/**
* Calling this method would pause the recording if it is currently running or resume if it is paused. Toggles the value `isPaused`
*/
const togglePauseResume: () => void = () => {
const togglePauseResume: () => void = useCallback(() => {
if (isPaused) {
setIsPaused(false);
mediaRecorder?.resume();
Expand All @@ -112,7 +125,7 @@ const useAudioRecorder: (
_stopTimer();
mediaRecorder?.pause();
}
};
}, [mediaRecorder, setIsPaused, _startTimer, _stopTimer]);

return {
startRecording,
Expand Down

0 comments on commit d2200d3

Please sign in to comment.