Skip to content

Commit

Permalink
enhance: Simplify useCache() logic with demorgan's law
Browse files Browse the repository at this point in the history
  • Loading branch information
ntucker committed Jul 28, 2024
1 parent 9620893 commit aa4dac5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/afraid-games-repair.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@data-client/react': patch
---

useCache() logic simplification (no real change)
6 changes: 4 additions & 2 deletions packages/react/src/hooks/useCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,21 +52,23 @@ export default function useCache<
key,
]);

// If we are hard invalid we must fetch regardless of triggering or staleness
const forceFetch = expiryStatus === ExpiryStatus.Invalid;

/*********** This block is to ensure results are only filled when they would not suspend **************/
// This computation reflects the behavior of useResource/useRetrive
// This computation reflects the behavior of useSuspense/useFetch
// It only changes the value when expiry or params change.
// This way, random unrelated re-renders don't cause the concept of expiry
// to change
const expired = useMemo(() => {
return !((Date.now() <= expiresAt && !forceFetch) || !key);
return (Date.now() > expiresAt || forceFetch) && key;
// we need to check against serialized params, since params can change frequently
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [expiresAt, key, forceFetch, state.lastReset]);

// fully "valid" data will not suspend/loading even if it is not fresh
const loading = expiryStatus !== ExpiryStatus.Valid && expired;
/****************************************************************************************************/

return useMemo(() => {
// if useSuspense() would suspend, don't include entities from cache
Expand Down

0 comments on commit aa4dac5

Please sign in to comment.