Reputation: 21
I'm new to Functional Components in React and was wondering how I would convert the code below from functional based to class based. I have had a go but I've had troubles around "React.useEffect".
Any help would be greatly appreciated! :)
(Also a further question, would you say it's better I learn functional components over class based?)
Code
import { Component } from "react";
import "./App.css";
import React from "react";
import audio from "./250629__kwahmah-02__alarm1.mp3";
import UIfx from "uifx";
import { render } from "@testing-library/react";
function Timer() {
const [time, setTime] = React.useState(0);
const [timerOn, setTimeOn] = React.useState(false);
React.useEffect(() => {
let interval = null;
if (timerOn) {
interval = setInterval(() => {
setTime((prevTime) => prevTime + 1); // We wanna increase the time every 10 milliseconds
}, 1000);
} else {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [timerOn]);
return (
<div className="App">
<header className="App-header">
{/* <div>{time}</div> */}
<div>
<h1>
{("0" + parseInt(time / 3600)).slice(-2)}:
{("0" + parseInt((time / 60) % 60)).slice(-2)}:
{("0" + parseInt(time % 60)).slice(-2)}
</h1>
</div>
<div>
{!timerOn && time === 0 && (
<button id="StartTimer" onClick={() => setTimeOn(true)}>
Start
</button>
)}
{timerOn && (
<button id="PauseTimer" onClick={() => setTimeOn(false)}>
Pause
</button>
)}
{!timerOn && time !== 0 && (
<button id="ResumeTimer" onClick={() => setTimeOn(true)}>
Resume
</button>
)}
{!timerOn && time > 0 && (
<button id="ResetTimer" onClick={() => setTime(0)}>
Reset
</button>
)}
</div>
</header>
</div>
);
}
export default Timer;
Upvotes: 1
Views: 57
Reputation: 1787
Side-effects in class components are handled with componentDidMount
and componentDidUpdate
So your useEffect
hook will turn into something like this:
componentDidUpdate() {
let interval = null;
if (timerOn) {
interval = setInterval(() => {
setTime((prevTime) => prevTime + 1); // We wanna increase the time every 10 milliseconds
}, 1000);
} else {
clearInterval(interval);
}
}
Keep in mind that any cleanup like clearInterval(interval)
is now must be made at componentWillUnmount
lifecycle method
But it is recommended to use functional components.
Upvotes: 1