DEV Community

Jorjis Hasan
Jorjis Hasan

Posted on

πŸ›€ CleanUp in React

Task: Do something after the initial render happens. For instance, log this text ("Hey jorjis, close me ❌") in the console after every second.

Solution:

import { useEffect} from "react";

const User = () => {

  useEffect(() => {
    setInterval(() => {
      console.log("Hey jorjis, close me ❌");
    }, 1000);
  }, []);

  return (
    <div className="user-card">
      <h1>Name: Jorjis</h1>
      <h2>Location: Dhaka, Bangladesh</h2>
      <p>Contact: speak.jorjis@gmail.com</p>
    </div>
  );
};

export default User;
Enter fullscreen mode Exit fullscreen mode

WHAT do you think ? Will this code work ? 🧐

Okay, let's visualize the outcome:

A preview of code output

Explanation: Our app requires at least two pages to understand the underlying concept. So, I set up accordingly. Let's zoom in on what's going on here.

  • Our code works as we wanted, right?
  • There is a glitch. So, When I go from the 'About' page to the 'Contact' page, this function called setInterval is supposed to stop, but it doesn't. And then, when I come back to the 'About' page from the 'Contact' page, the setInterval function runs faster than before. It's because another setInterval function is scheduled to run.
  • it will schedule numbers of the setInterval function as I navigate back and forth to the about page.
  • which might lead to memory leaks. We need to build our CLEANUP logic to fix it right away.

Corrected Code (functional-component):

import { useEffect} from "react";

const User = () => {
  useEffect(() => {
    const timer = setInterval(() => {
      console.log("Hey jorjis, close me ❌");
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);
  return (
    <div className="user-card">
      <h1>Name: Jorjis</h1>
      <h2>Location: Dhaka, Bangladesh</h2>
      <p>Contact: speak.jorjis@gmail.com</p>
    </div>
  );
};

export default User;
Enter fullscreen mode Exit fullscreen mode

Here, I return a callback function from useEffect. The callback function will be invoked after the component is unmounted. And I wrote the cleanUp logic as the task required.

Now, we'll see how we used to write react code to get this functionality, which refers to refactoring our react code in the class component.

In Class Component:

import {React} from 'react';

class UserClass extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.timer = setInterval(() => {
      console.log("Hey jorjis, close me ❌");
    }, 1000);
  }

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

  render() {
    return (
    <div className="user-card">
      <h1>Name: Jorjis</h1>
      <h2>Location: Dhaka, Bangladesh</h2>
      <p>Contact: speak.jorjis@gmail.com</p>
    </div>
    );
  }
}

export default UserClass;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)