-
Notifications
You must be signed in to change notification settings - Fork 75
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat:
useMemoWithPrevious
React hook
- Loading branch information
Showing
2 changed files
with
43 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { DependencyList, useEffect, useMemo, useRef, useState } from 'react'; | ||
|
||
export const useMemoWithPrevious = <T,>( | ||
factory: () => T, | ||
deps: DependencyList, | ||
{ initialPrev }: { initialPrev?: T } | undefined = {}, | ||
) => { | ||
const prevRef = useRef(initialPrev); | ||
const [prevResetKey, setPrevResetKey] = useState({}); | ||
|
||
const current = useMemo(factory, deps); | ||
const memoizedPrev = useMemo(() => { | ||
return prevRef.current; | ||
// Only update when the reset key changes and deps change | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [...deps, prevResetKey]); | ||
|
||
useEffect(() => { | ||
prevRef.current = current; | ||
// Only update when deps change | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, deps); | ||
|
||
return [ | ||
{ | ||
previous: memoizedPrev, | ||
current: current, | ||
}, | ||
{ | ||
resetPrevious: () => { | ||
prevRef.current = initialPrev; | ||
setPrevResetKey({}); | ||
}, | ||
}, | ||
] as const; | ||
}; |