Skip to content

Commit

Permalink
feat(usePrevious): reworked the hook, now it is more memory-efficient.
Browse files Browse the repository at this point in the history
Better to use two-variables exchange than `useEffect` with new
function on each render.
  • Loading branch information
xobotyi committed Jun 15, 2020
1 parent 8fb9d05 commit 8c6f467
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/usePrevious.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { useEffect, useRef } from 'react';
import { useRef } from 'react';

const usePrevious = <T>(state: T): T | undefined => {
const ref = useRef<T>();
export default function usePrevious<T>(state: T): T | undefined {
const curRef = useRef<T>();
const prevRef = useRef<T>();

useEffect(() => {
ref.current = state;
});
prevRef.current = curRef.current;
curRef.current = state;

return ref.current;
};

export default usePrevious;
return prevRef.current;
}

0 comments on commit 8c6f467

Please sign in to comment.