Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
useConst()
Stable. Performant. Simple.
The missing brick of stability
Local stable storage associated with the component's lifecycle is needed quite often. Typically,
useRef
/useState
used for this. However, there are cases when this is not practicaluseState
runs dead code ifsetState
is not going to be usedstate
of auseState
should not be considered stable, even ifsetState
omitteduseRef
, inside render, results in all but first object to be garbageref.current
afterref = useRef()
to avoid garbage produces boilerplate code{ current: T }
box is unnecessaryThis is solved by using a custom hook that utilizes
useRef
and returns thecurrent
propertyThere are also a number of libraries that do this
Examples
Yup, it has to run an excessive check, and even box the value second time, just because of no access to hooks dispatchers, to separate a hook living phases. It looks like creating a simple thing by complicating a more complex tool designed for different thing.
This is acceptable, as it gives the desired result, and as the only available option. But then eslint starts to warn about the need to add references to other hooks dependencies.
Here are some of the issues related to that: #16873 #19125 #20205 #20477 #20752
Arguments for not allowing to specify in the
eslint-plugin-react-hooks
settings which custom hooks should be considered stable seem convincing.It feels like something is just missing. The absence of it pushes to create workarounds and the need of workarounds to close issues produced by that. Something that should have been there from the start and revealed along with
useRef
anduseState
. So simple, thatuseRef
anduseState
could have been inherited from, if there was such a need. And here is where one may give up and specify references. Or try to make it right