Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(refactor/react): Memoize ComponentScope unique value with useState to ensure referential stability. #73

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/react/useScopes.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useContext, useEffect, useMemo, useState } from "react";
import { MoleculeScopeOptions } from "../shared/MoleculeScopeOptions";
import { dstream } from "../shared/getDownstreamScopes";
import { ComponentScope, ScopeTuple } from "../vanilla";
Expand Down Expand Up @@ -56,13 +56,17 @@ export function useScopes(
export function useScopeTuplesRaw(options?: MoleculeScopeOptions) {
const parentScopes = useContext(ScopeContext);

const generatedValue = useMemo(
() => new Error("Do not use this scope value. It is a placeholder only."),
[],
);
// `useState` instead of `useMemo`, so React cannot discard the cached value.
const [componentScopeTuple] = useState(() => {
// We only care about referential stability, so this value can be any object.
const generatedValue = new Error(
"Do not use this scope value. It is a placeholder only.",
);

const componentScopeTuple = useRef([ComponentScope, generatedValue] as const)
.current as ScopeTuple<unknown>;
return [ComponentScope, generatedValue] as ScopeTuple<unknown>;
});

const generatedValue = componentScopeTuple[1];

const inputTuples: AnyScopeTuple[] = (() => {
if (!options) return [...parentScopes, componentScopeTuple];
Expand Down