React Native's Controlled Switch Component
The Switch component is a 'controlled' input; it doesn't manage its own state. You use it for on/off settings by telling it what to display via the `value` prop and updating that state in the `onValueChange` callback. The footgun is forgetting this link.
WHY IT EXISTS The Switch component exists to provide a standard, platform-native toggle for boolean (true/false) user inputs. It ensures a familiar look and feel for on/off settings across both iOS and Android without you having to build it from scratch.
THE MENTAL MODEL Think of the Switch as a puppet, and your app's state is the puppeteer. The component is 'controlled,' meaning it doesn't have its own internal on/off state. It only displays the boolean value you pass to it and reports when a user wants to change that value.
HOW IT WORKS The flow is a simple loop: First, the Switch renders based on its value prop (e.g., value={true} shows it as 'on'). Second, when the user taps it, the onValueChange callback fires with the new proposed value. Third, in that callback, you must update your app's state. Finally, the component re-renders with the new value from your state, completing the visual change. If you miss the third step, the value prop never changes, and the switch will appear to snap back to its original position, ignoring the user's tap.
WHEN TO USE IT Use the Switch for any binary setting that a user can toggle. Common examples include enabling dark mode, turning notifications on or off, or agreeing to terms and conditions.
WHEN NOT TO USE IT Avoid using a Switch for actions that are not state changes. For a one-time action like 'Submit' or 'Send', a Button is more appropriate. For selecting one option from a list of many, use a Picker or a custom radio button group.
ONE CANONICAL EXAMPLE To make a Switch work, you connect a state variable to its props. For example, you would declare state like const [isNotificationsEnabled, setNotificationsEnabled] = useState(false);. Then, you would render the component like this: <Switch onValueChange={newValue => setNotificationsEnabled(newValue)} value={isNotificationsEnabled} /> Here, value reads from the state, and onValueChange writes back to it.
Read the original → reactnative.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.