Consider this React Native component using useState. What will be displayed after pressing the button twice?
import React, { useState } from 'react'; import { View, Text, Button } from 'react-native'; export default function Counter() { const [count, setCount] = useState(0); return ( <View> <Text>{count}</Text> <Button title="Add" onPress={() => setCount(count + 1)} /> </View> ); }
Each button press increases the count by 1.
The initial count is 0. Pressing the button twice calls setCount(count + 1) two times, increasing count to 2.
What will be the final value of count after pressing the button once in this React Native component?
import React, { useState } from 'react'; import { View, Text, Button } from 'react-native'; export default function LoopCounter() { const [count, setCount] = useState(0); const handlePress = () => { for (let i = 0; i < 3; i++) { setCount(count + 1); } }; return ( <View> <Text>{count}</Text> <Button title="Add 3" onPress={handlePress} /> </View> ); }
Remember that state updates are asynchronous and do not immediately update count inside the loop.
Each setCount(count + 1) uses the same count value (0) because state updates are batched. So after the loop, count becomes 1, not 3.
Which code snippet correctly uses useState with a function to set the initial state lazily?
Lazy initialization requires passing a function that returns the initial value.
Option B correctly passes a function that calls expensiveComputation() and returns its result lazily. Option B calls the function immediately. Option B returns undefined because of missing return. Option B returns the function itself, not the result.
In this React Native component, why does the displayed count not update immediately after calling setCount(count + 1) twice in a row?
import React, { useState } from 'react'; import { View, Text, Button } from 'react-native'; export default function DoubleIncrement() { const [count, setCount] = useState(0); const incrementTwice = () => { setCount(count + 1); setCount(count + 1); }; return ( <View> <Text>{count}</Text> <Button title="Increment Twice" onPress={incrementTwice} /> </View> ); }
Think about how state values are captured in closures.
Both setCount calls use the same count value from the closure (stale value). So the state only increments by 1, not 2.
You want to increment a counter state three times in a single button press. Which approach ensures the count increases by 3?
Remember how React batches state updates and how to use the updater function form.
Option A uses the functional updater form, which correctly increments the state three times by applying each update to the latest state. Option A uses stale state and increments only once. Option A increments by 3 once but may cause issues if state updates are asynchronous. Option A returns a function instead of a value, causing errors.