Consider two sibling components that share a counter state lifted up to their parent. What will be displayed when you press the increment button in one sibling?
import React, { useState } from 'react'; import { View, Text, Button } from 'react-native'; function SiblingA({ count, onIncrement }) { return <Button title={`Increment A (${count})`} onPress={onIncrement} />; } function SiblingB({ count }) { return <Text>Count in B: {count}</Text>; } export default function Parent() { const [count, setCount] = useState(0); return ( <View> <SiblingA count={count} onIncrement={() => setCount(count + 1)} /> <SiblingB count={count} /> </View> ); }
Think about where the state is stored and which components receive it as props.
The state count is stored in the parent component. Both siblings receive count as a prop. When the button in SiblingA is pressed, it calls onIncrement which updates the parent's state. This causes both siblings to re-render with the new count value.
What is the main reason to lift state up to a common parent component in React Native?
Think about components that need to show the same data or react to the same changes.
Lifting state up allows sibling components to share the same state from their common parent. This keeps their data consistent and synchronized.
In React Native, when a parent component's state changes due to lifting state up, what happens to its child components?
Remember how React updates components when props change.
When the parent's state changes, React re-renders the parent and all children receiving props from that state. This updates the UI to reflect the new data.
Given this React Native code snippet, why does Child's console.log not show updates to count when the button in Parent is pressed?
import React, { useState, useEffect } from 'react'; import { View, Text, Button } from 'react-native'; function Parent() { const [count, setCount] = useState(0); return ( <View> <Button title="Increment" onPress={() => setCount(count + 1)} /> <Child count={count} /> </View> ); } function Child({ count }) { useEffect(() => { console.log('Count changed:', count); }, []); return <Text>{count}</Text>; }
Look at the dependencies of the useEffect hook in Child.
The Child component's useEffect runs only once on mount because its dependency array is empty. Although the count prop changes and the component re-renders, the effect does not run again to log the new count.
In a React Native app using React Navigation, if you lift state up to a parent component that wraps multiple screens, what is a key effect on navigation?
Think about where the state lives relative to the navigation container.
Lifting state up to a parent component that wraps multiple screens keeps the state alive while navigating. This allows screens to share and persist data without resetting.