1

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;
1
  • 1
    Its better to use functional components (hooks) over class components. reactjs.org/docs/… As per this, 'In the longer term, we expect Hooks to be the primary way people write React components.' Commented Jul 5, 2021 at 11:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.