Batch state updates in useInput
callback
#581
Merged
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.
Currently, Ink will rerender as soon as state is updated. As a result, if a component has 2
useState
hooks and both of them need to be updated at once, it will actually result in 2 rerenders, not 1.Pressing i will lead to the following output:
Ideally there shouldn't be an intermediate render for "X = 2 Y = 1", which occurs after
setX
is called and Ink should only rerender aftersetY
.Fortunately,
batchedUpdates
function from React reconciler allows Ink to do just that. React DOM automatically batches state updates in event handlers, but Ink doesn't have the concept of DOM events, so this PR usesbatchedUpdates
to calluseInput
's callback to simulate React DOM's behavior.If we run the previous example code in this branch and press i, the output will be:
Thanks to this, Ink UIs will become much smoother without any changes to their code.