ahooks源码学习之useInterval

3,304 阅读1分钟

useInterval

简化reactsetInterval的使用的hooks

实现一个倒计时的功能

示例Demo

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

const style = {
    width: '60px',
    height: '60px',
    borderRadius: '30px',
    background: 'rgba(0,0,0,.5)',
    textAlign: 'center',
    lineHeight: '60px',
    color: 'white',
    margin: '100px'
}

export default function Test() {
    const [count, setCount] = useState(60);

    useEffect(() => {
        const interval = setInterval(() => {
            setCount(c => c - 1);
        }, 1000);
        return () => {
            clearInterval(interval);
        }
    }, [])


    return (
        <div style={style}>{count}s</div>
    )
}

这种实现其实还是有很多代码量的,我们这是时候可能就会想,有没有一个好用的hooks,像useState一样好用,于是我们可以实现一个useInterval

useInterval实现

import { useEffect, useRef } from 'react';

/**
 * 
 * @param {*} fn 回调函数
 * @param {*} delay 延迟时间
 * @param {*} options {immediate} 是否立即执行
 */
function useInterval(
    fn,
    delay,
    options,
) {
    const immediate = options?.immediate;
    const fnRef = useRef();
    fnRef.current = fn;

    useEffect(() => {
        if (typeof delay !== 'number' || delay < 0) return;
        if (immediate) {
            fnRef.current();
        }
        const timer = setInterval(() => {
            fnRef.current();
        }, delay);
        return () => {
            clearInterval(timer);
        };
    }, [delay]);
}

export default useInterval;

使用

有了这个useIntervalhooks我们就可以轻松实现上的事例了

useInterval(() => {
    setCount(c => c - 1);
},1000)

同时我们还可以停止定时器,如下

setInterval(undefined);

API

useInterval(
  fn: () => void, 
  delay?: number | undefined, 
  options?: Options
);

Params

参数说明类型
fn要定时调用的函数() => void
delay间隔时间,当取值 undefined 时会停止计时器numberundefined
options配置计时器的行为Options

Options

参数说明类型默认值
immediate是否在首次渲染时立即执行booleanfalse