模拟
2024年01月28日
一、认识
二、实现
2.1 /hooks/useRafState.tsx
import useUnmount from './useUnmount';
import { useCallback, useRef, useState } from 'react';
function useRafState(initialState) {
const ref = useRef(0);
const [state, setState] = useState(initialState);
const setRafState = useCallback(value => {
cancelAnimationFrame(ref.current);
ref.current = requestAnimationFrame(() => {
setState(value);
});
}, []);
useUnmount(() => {
cancelAnimationFrame(ref.current);
});
return [state, setRafState];
}
export default useRafState;
2.2 /hooks/useUnmount.tsx
import { useEffect } from 'react';
import useLatest from './useLatest';
function useUnmount(fn) {
const fnRef = useLatest(fn);
useEffect(
() => () => {
fnRef.current();
},
[]
);
}
export default useUnmount;
2.3 /hooks/useLatest.tsx
import { useRef } from 'react';
function useLatest(value) {
const ref = useRef(value);
ref.current = value;
return ref;
}
export default useLatest;