Challenge - 5 Problems
State Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Understanding useState vs useReducer
Which statement best describes when to prefer useReducer over useState in React Native?
Attempts:
2 left
💡 Hint
Think about complexity and how state updates depend on previous values.
✗ Incorrect
useReducer is preferred for complex state logic or when the next state depends on the previous state. useState is simpler and better for simple state updates.
❓ ui_behavior
intermediate2:00remaining
Effect of Context API on component re-renders
In React Native, what happens to components consuming a Context when the Context value changes?
Attempts:
2 left
💡 Hint
Consider how Context propagates changes to consumers.
✗ Incorrect
When Context value changes, all consuming components re-render because React cannot know which parts of the value changed.
❓ lifecycle
advanced2:00remaining
State update timing with useState and useEffect
Given this React Native code snippet, what will be the console output after the button is pressed once?
code:
"""
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count changed:', count);
}, [count]);
const onPress = () => {
setCount(count + 1);
setCount(count + 1);
};
"""
Attempts:
2 left
💡 Hint
Remember that state updates are asynchronous and may be batched.
✗ Incorrect
Both setCount calls use the same stale count value (0), so the state updates to 1 only once. The effect logs 'Count changed: 1'.
advanced
2:00remaining
State persistence across React Navigation screens
In React Native using React Navigation, which approach ensures state persists when navigating back and forth between screens?
Attempts:
2 left
💡 Hint
Think about where state lives when screens unmount and remount.
✗ Incorrect
Local state in components resets when screens unmount. Global state or context persists across navigation.
🔧 Debug
expert2:00remaining
Identifying cause of stale state in React Native
Why does this React Native component always log the initial count value 0 when the button is pressed, despite updating state?
code:
"""
const MyComponent = () => {
const [count, setCount] = useState(0);
const handlePress = () => {
setTimeout(() => {
console.log('Count is:', count);
setCount(count + 1);
}, 1000);
};
return ;
};
"""
Attempts:
2 left
💡 Hint
Consider how closures capture variables in JavaScript functions.
✗ Incorrect
The handlePress function closes over the initial count value 0, so the delayed callback always sees count as 0, causing stale logs and increments.