2

My code right now picks a date, and this class is used in another file. Where it renders the date in a ddd D MMMM format. I want to change my code from a class to a react hook, and I'm not very sure how to do this. Here is the code:

import React, { Component } from "react";
import moment from "moment";
 
class DayPicker extends Component {
  constructor(props) {
    super(props);
    this.state = { date: Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: Date(),
    });
  }

  render() {
    return (
      <div className={style.dayPicker}>
        {moment()
          .add(daysToAdd ? daysToAdd : 0, "day")
          .format("ddd D MMMM")}
      </div>
    );
  }
}

export default DayPicker;

If someone manages to convert my code into react hooks, please explain the process to me as it would be a great change to learn more about react Hooks.

1
  • I have managed to figure it out Commented Jun 29, 2023 at 22:34

1 Answer 1

2

You need to keep in mind the following things which converting the classes to functional components with hooks.

First: use useState hook in place of state.

Second: change lifecycle methods to useEffect hooks.

Third: Change classes variables to useRef.

import React, { useState, useEffect } from "react";
import moment from "moment";

const DayPicker = ()=> {
  const [date, setDate] = useState(new Date());

  const timerID = useRef(null);
  useEffect(() => {
     timerID.current = setInterval(() => tick(), 1000);

     return () => {
        // This function will execute on unmount
        clearInterval(timerID.current);
     }
  }, []) // empty array here signifies that the effect will be run once on initial mount


  const tick = () => {
    setDate(new Date())
  }

    return (
      <div className={style.dayPicker}>
        {moment()
          .add(daysToAdd ? daysToAdd : 0, "day")
          .format("ddd D MMMM")}
      </div>
    );
}

export default DayPicker;

For a detailed understanding of each of these hooks, read the React docs.

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

2 Comments

in this you could also take out the function tick() and just call setDate(new Date()) by itself in setInterval
@BradBall, yes we could do that as well, but I didn't want to confuse the OP

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.