Skip to content

Commit

Permalink
perf(shared/useWatch): 优化 useWatch,从异步回调改为同步
Browse files Browse the repository at this point in the history
  • Loading branch information
mengxinssfd committed Aug 14, 2023
1 parent 5a06218 commit 2ebaffa
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
4 changes: 4 additions & 0 deletions packages/shared/src/hooks/tests/useWatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import { sleep } from '@tool-pack/basic';
describe('useWatch', () => {
test('common', async () => {
let no: (number | void)[] = [];
let renderTimes = 0;
const { result } = renderHook(() => {
renderTimes++;
const [state, setState] = useState(1);
useWatch(state, (newVal, oldVal) => {
times++;
Expand All @@ -30,6 +32,8 @@ describe('useWatch', () => {
expect(result.current[0]).toBe(3);
expect(times).toBe(2);
expect(no).toEqual([3, 2]);

expect(renderTimes).toBe(3);
});
test('immediate', async () => {
let times = 0;
Expand Down
15 changes: 7 additions & 8 deletions packages/shared/src/hooks/useWatch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef } from 'react';
import { useRef } from 'react';

export function useWatch<T>(
value: T,
Expand All @@ -9,15 +9,14 @@ export function useWatch<T>(
const isInitRef = useRef(true);
const canceledRef = useRef(false);

useEffect(() => {
if (canceledRef.current) return;
// eslint-disable-next-line @typescript-eslint/no-empty-function
if (canceledRef.current) return () => {};

const oldVal = oldValRef.current;
if (value === oldVal) return;

oldValRef.current = value;
const oldVal = oldValRef.current;
oldValRef.current = value;
if (oldVal !== value) {
cb(value, oldVal);
}, [cb, value]);
}

// immediate
if (immediate && isInitRef.current) cb(value);
Expand Down

0 comments on commit 2ebaffa

Please sign in to comment.