Fix handling of controlled state in toggle-able controls #3834
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.
Platforms Impacted
Description of changes
The hook we use to handle toggle events, useAsToggleWithEvent, does not properly take controlled state into account. In particular it updates its internal state regardless of whether the check state is controlled and doesn't apply state applied from the parent correctly, which means that when its checked state is applied via not toggling the control directly, the state becomes out of sync with that the app believes its state should be.
For example, if a checkbox is meant to be controlled and toggling it fires an event to a parent, the behavior would look like:
Fix is to use the useControllableValue hook to store current checked state, which takes controlled state into account when tracking a boolean's value.
Verification
New test added for the case where a controlled checkbox is inside a Pressable and both can toggle the checked state:
Ensured test above toggles as expected with various configurations of toggling via checkbox as well as external controls (Pressable, the buttons).
Tested uncontrolled checkboxes
Tested switches, toggle button
Pull request checklist
This PR has considered (when applicable):