How to call a function every minute in a React component?

You want to initiate a timeout function inside a lifecycle method.

Lifecycle methods are methods which call on, for example, mount and unmount (there are more examples but for the sake of explanation I will stop here)

what you’re interested in is the mount lifecycle.

In functional components, it can be accessed like this:

import { useEffect } from 'react';

useEffect(() => {
  // This will fire only on mount.
}, [])

In that function, you want to initialize a setTimeout function.

const MINUTE_MS = 60000;

useEffect(() => {
  const interval = setInterval(() => {
    console.log('Logs every minute');
  }, MINUTE_MS);

  return () => clearInterval(interval); // This represents the unmount function, in which you need to clear your interval to prevent memory leaks.
}, [])

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)