codeQ Blog

Chào mừng mọi người đã đến với codeQ Blog

Custom hooks: useInterval

Đăng vào ngày
Cover Image for Custom hooks: useInterval

Bạn viết 1 custom hook như dưới đây: useInterval.js

import {useEffect, useRef} from 'react';

function useInterval(callback, delay) {
  const refCallback = useRef(callback);

  useEffect(() => {
    refCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (delay === null) {
      return;
    }

    const id = setInterval(() => refCallback.current(), delay);

    return () => clearInterval(id);
  }, [delay]);
}

export default useInterval;

Sau đó sử dụng:

import React, {useState} from 'react';
import {Text, View} from 'react-native';
import useInterval from './useInterval';

const CountComponent = () => {
  const [count, setCount] = useState(0);

  useInterval(() => {
    setCount(count + 1);
  }, 1000);

  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      <Text style={{fontSize: 60}}>{count}</Text>
    </View>
  );
};

export default CountComponent;

Như vậy là xong. Chúc các bạn thành công. :)