Skip to content

Commit 8c6f467

Browse files
committed
feat(usePrevious): reworked the hook, now it is more memory-efficient.
Better to use two-variables exchange than `useEffect` with new function on each render.
1 parent 8fb9d05 commit 8c6f467

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

src/usePrevious.ts

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
import { useEffect, useRef } from 'react';
1+
import { useRef } from 'react';
22

3-
const usePrevious = <T>(state: T): T | undefined => {
4-
const ref = useRef<T>();
3+
export default function usePrevious<T>(state: T): T | undefined {
4+
const curRef = useRef<T>();
5+
const prevRef = useRef<T>();
56

6-
useEffect(() => {
7-
ref.current = state;
8-
});
7+
prevRef.current = curRef.current;
8+
curRef.current = state;
99

10-
return ref.current;
11-
};
12-
13-
export default usePrevious;
10+
return prevRef.current;
11+
}

0 commit comments

Comments
 (0)