Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
garronej committed Mar 21, 2024
1 parent 02c1741 commit 9143bd0
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/tools/useGuaranteedMemo.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { useRef } from "react";
import { useState } from "react";

/** Like react's useMemo but with guarantee that the fn
* won't be invoked again if deps hasn't change */
export function useGuaranteedMemo<T>(
fn: () => T,
deps: React.DependencyList
): T {
const ref = useRef<{ v: T; prevDeps: unknown[] }>();
const [ref] = useState<{
current: { v: T; prevDeps: unknown[] } | undefined;
}>({ "current": undefined });

if (
!ref.current ||
ref.current === undefined ||
deps.length !== ref.current.prevDeps.length ||
ref.current.prevDeps.map((v, i) => v === deps[i]).indexOf(false) >= 0
) {
Expand Down

0 comments on commit 9143bd0

Please sign in to comment.