Skip to content

Latest commit

 

History

History
23 lines (16 loc) · 688 Bytes

use-interval.md

File metadata and controls

23 lines (16 loc) · 688 Bytes

How to use setInterval

If you use setInterval as you usually do within a React component, the state won't be persisted. In order to fix this, you should use a custom hook that Dan Abramov wrote:

import React, { useState, useEffect, useRef } from 'react';

function Counter() {
  let [count, setCount] = useState(0);

  useInterval(() => {
    // Your custom logic here
    setCount(count + 1);
  }, 1000);

  return <h1>{count}</h1>;
}

useInterval can be installed with npm install --save use-interval

References: