Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Summary: Changelog: [Internal] - Update Switch to allow injected implementations ## General understanding of the component The main flow of Switch is pretty straightforward, basically passing the props to the respective native component which uses the platform switch views on Android / iOS The interesting parts of Switch is the fact that it's a controlled component -- meaning that this component sees the JS value prop as the source of truth about the state of this component and any time the native value of the switch is out of sync with the JS value prop, we send a command `setNativeValue` to keep those in sync. The problems I ran into: * Keeping native and JS in sync * Switch skips animation occassionally on iOS simulator ## How we keep native and JS in sync By construction, the native value of the component should be the same as JS value. Then, we know the native value has changed whenever the callback `handleChange` has been fired. **Before** In the handleChange callback, we'd set an [instance variable `lastNativeValue` with the updated value](https://fburl.com/diffusion/nangxzoh) and force update. Then, in `componentDidUpdate`, we'd send the native commands if we determine that `lastNativeValue` and the `value` prop were out of sync. **After** For our modern implementation, we store the value of the switch as reported by `handleChange` and check it against the `props.value` of the switch. If they are out of sync then we will update the native switch via the switch command. **Why is `native` an object?** We need to run the `useLayoutEffect` every time `handleChange` is called independent of the value of the switch. **Why not move the logic of dispatching commands to `handleChange`?**? This would change behavior from old implementation where we would call `onChange` handlers and then re-render. Additionally, the logic to run the native commands were on `componentDidUpdate` which would've run when any prop changed. We can simplify this down to caring only when `props.value` updates. ## Unsolved, existing issue: Switches skip animation occasionally * This occurs both in the modern and old versions of Switch and I've only seen this on iOS simulators. It occurs most frequently in the "events" example where two switches' values are synced and most often the first transition after we navigate to the example surface. I have not been able to reproduce this behavior on device. * Something must be triggering a re-render in the middle of native's animation.. {F564595576} Reviewed By: nadiia, kacieb Differential Revision: D27381306 fbshipit-source-id: 06d13c6fe1ff181443f4b8dd27fb1ac65e071962
- Loading branch information