Skip to content

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

Open
Iwo Plaza (iwoplaza) wants to merge 1 commit intosaasquatch:mainfrom
iwoplaza:impr/component-scope-tuple-stability
Open

(refactor/react): Memoize ComponentScope unique value with useState to ensure referential stability.#73
Iwo Plaza (iwoplaza) wants to merge 1 commit intosaasquatch:mainfrom
iwoplaza:impr/component-scope-tuple-stability

Conversation

@iwoplaza
Copy link

Description of the change

According to React Docs, useMemo's result can be forgotten under special circumstances. To avoid this potential behavior, we could use useState to create a stable reference to both the tuple and the generated value at the same time. What do you think?

Type of change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation or Development tools (readme, specs, tests, code formatting)

@loganvolkers
Copy link
Member

Thank you for the PR

@Wendystraite
Copy link
Contributor

Do you think this is possible to have a failing test without this fix ?

As I can see from the doc (https://react.dev/reference/react/useMemo) :

React will not throw away the cached value unless there is a specific reason to do that. For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should be fine if you rely on useMemo solely as a performance optimization. Otherwise, a state variable or a ref may be more appropriate.

@Wendystraite
Copy link
Contributor

Wendy Fouchter (Wendystraite) commented Oct 11, 2025

Well I didn't succeed in doing a test case but you are right : useState is semantically more appropriate since it guarantees both componentScopeTuple and generatedValue to remain stable where now only componentScopeTuple is stable (with useRef).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants