COVID19 Lockdown Dev Log – Day 17, setInterval Memory Leak

What I Worked On

Fixing a memory leak, SEO optimizations and general styling fixes. All in my portfolio

What I Learned

Let’s leave the SEO optimizations and general styling fixes out and just focus on the memory leak.

I am using a timer to simulate a loading screen in my portfolio and I noticed that my console was warning me about a memory leak. I took a look at my code:

// loading.js

import React, { Component } from "react";

class Loading extends Component {
    constructor(props) {
        super(props)
        this.state = {
            interval: setInterval(this.startInterval, 1200)
        }
    }

    startInterval = () => {
        this.setState({
            isLoaded: true,
        })
    }

    render() {
        return (
        //... JSX code
        )
    }
}

export default Loading;

I have worked with timers in other languages before and you would usually have to stop it at some point so it doesn’t fire infinetly. The same applies in JavaScript and after reading up on the documentation I found a way to stop the timer with the ‘clearInterval’ JavaScript function:

// loading.js

import React, { Component } from "react";

class Loading extends Component {
    constructor(props) {
        super(props)
        this.state = {
            interval: setInterval(this.startInterval, 1200)
        }
    }

    startInterval = () => {
        this.setState({
            isLoaded: true,
        })
    }

    componentWillUnmount() {
        clearInterval(this.state.interval);
    }

    render() {
        const elements = [".", ".", "."]

        return (
         //...JSX code
        )
    }
}

export default Loading;

In React you typically do the “clean up” in ‘componentWillUnmount’. This function runs when a component is about to unmount, which in this case is when the loading screen dissappears. Adding the ‘clearInterval’ function fixes the memory leak and I have no more warnings in my console! 😀

What Distracted Me During The Day

  • GF and I went for cake 😀
  • Messenger