current position:Home>Ahooks source code interpretation series - 7

Ahooks source code interpretation series - 7

2021-08-27 10:31:22 Front end shift student

This series will ahooks Everything in it hook The source code is interpreted , By reading ahooks To get familiar with custom hook Writing , Improve your ability to write custom hook The ability of , I hope it can help you .

To distinguish from the original comments of the code , The personal understanding part uses /// start , Here and Three slashes command It doesn't matter. , Just to distinguish .

Looking back

What's Monday for ? Of course, a refreshing article first ahooks Source code interpretation ~ Enter today SideEffect Part of the ahooks.

SideEffect

useDebounceFn

Yes lodash.debounce Encapsulation

import debounce from 'lodash.debounce';
import { useRef } from 'react';
import useCreation from '../useCreation';
import { DebounceOptions } from '../useDebounce/debounceOptions';
import useUnmount from '../useUnmount';

type Fn = (...args: any) => any;

function useDebounceFn<T extends Fn>(fn: T, options?: DebounceOptions) {
  const fnRef = useRef<T>(fn);
  fnRef.current = fn;

  const wait = options?.wait ?? 1000;
  ///  Change the target method to  debounce  edition 
  const debounced = useCreation(
    () =>
      debounce<T>(
        ((...args: any[]) => {
          return fnRef.current(...args);
        }) as T,
        wait,
        options,
      ),
    [],
  );

  useUnmount(() => {
    debounced.cancel();
  });

  return {
    run: (debounced as unknown) as T,
    cancel: debounced.cancel,
    flush: debounced.flush,
  };
}

export default useDebounceFn;

 Copy code 

useDebounce

Convert normal values to values with anti shake behavior

import { useState, useEffect } from 'react';
import useDebounceFn from '../useDebounceFn';
import { DebounceOptions } from './debounceOptions';

function useDebounce<T>(value: T, options?: DebounceOptions) {
  const [debounced, setDebounced] = useState(value);
  ///  Change the method of updating the status to the anti shake method 
  const { run } = useDebounceFn(() => {
    setDebounced(value);
  }, options);

  useEffect(() => {
    run();
  }, [value]);

  return debounced;
}

export default useDebounce;

 Copy code 

useThrottleFn

Yes lodash.throttle Encapsulation

import throttle from 'lodash.throttle';
import { useRef } from 'react';
import useCreation from '../useCreation';
import { ThrottleOptions } from '../useThrottle/throttleOptions';
import useUnmount from '../useUnmount';

type Fn = (...args: any) => any;

function useThrottleFn<T extends Fn>(fn: T, options?: ThrottleOptions) {
  const fnRef = useRef<T>(fn);
  fnRef.current = fn;

  const wait = options?.wait ?? 1000;
  ///  Convert the target method to a throttling version 
  const throttled = useCreation(
    () =>
      throttle<T>(
        ((...args: any[]) => {
          return fnRef.current(...args);
        }) as T,
        wait,
        options,
      ),
    [],
  );

  useUnmount(() => {
    throttled.cancel();
  });

  return {
    run: (throttled as unknown) as T,
    cancel: throttled.cancel,
    flush: throttled.flush,
  };
}

export default useThrottleFn;

 Copy code 

useThrottle

Convert normal values to values with throttling behavior

import { useState, useEffect } from 'react';
import useThrottleFn from '../useThrottleFn';
import { ThrottleOptions } from './throttleOptions';

function useThrottle<T>(value: T, options?: ThrottleOptions) {
  const [throttled, setThrottled] = useState(value);
  ///  Throttling the method of updating values 
  const { run } = useThrottleFn(() => {
    setThrottled(value);
  }, options);

  useEffect(() => {
    run();
  }, [value]);

  return throttled;
}

export default useThrottle;

 Copy code 

useInterval、useTimeout

“ A timer that will wipe your ass ”

import { useEffect, useRef } from 'react';

function useInterval( fn: () => void, delay: number | null | undefined, options?: { immediate?: boolean; }, ): void {
  const immediate = options?.immediate;

  const fnRef = useRef<() => void>();
  fnRef.current = fn;

  useEffect(() => {
    if (delay === undefined || delay === null) return;
    if (immediate) {
      fnRef.current?.();
    }
    const timer = setInterval(() => {
      fnRef.current?.();
    }, delay);
    return () => {
      ///  Don't worry about forgetting to clear the timer anymore 
      clearInterval(timer);
    };
  }, [delay]);
}

export default useInterval;

 Copy code 
import { useEffect } from 'react';
import usePersistFn from '../usePersistFn';

function useTimeout(fn: () => void, delay: number | null | undefined): void {
  const timerFn = usePersistFn(fn);

  useEffect(() => {
    if (delay === undefined || delay === null) return;
    const timer = setTimeout(() => {
      timerFn();
    }, delay);
    return () => {
      ///  Don't worry about forgetting to clear the timer anymore 
      clearTimeout(timer);
    };
  }, [delay, timerFn]);
}

export default useTimeout;

 Copy code 

The above contents are inevitably wrong due to my level , Welcome to discuss and feedback .

copyright notice
author[Front end shift student],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827103118570P.html

Random recommended