Consider this React Native code using Context API. What text will be displayed on the screen?
import React, { createContext, useContext } from 'react'; import { Text, View } from 'react-native'; const ThemeContext = createContext('light'); function DisplayTheme() { const theme = useContext(ThemeContext); return <Text>{`Theme is ${theme}`}</Text>; } export default function App() { return ( <ThemeContext.Provider value="dark"> <View> <DisplayTheme /> </View> </ThemeContext.Provider> ); }
Look at the value passed to ThemeContext.Provider and what useContext returns.
The ThemeContext.Provider sets the context value to "dark". The DisplayTheme component uses useContext to read this value and displays it. So the output is "Theme is dark".
In this React Native component using Context API, what will be the value of count after pressing the button two times?
import React, { createContext, useContext, useState } from 'react'; import { Button, Text, View } from 'react-native'; const CountContext = createContext(); function Counter() { const { count, setCount } = useContext(CountContext); return ( <View> <Text>{`Count: ${count}`}</Text> <Button title="Increment" onPress={() => setCount(count + 1)} /> </View> ); } export default function App() { const [count, setCount] = useState(0); return ( <CountContext.Provider value={{ count, setCount }}> <Counter /> </CountContext.Provider> ); }
Each button press increases count by 1. Starting from 0, two presses add 2.
The initial count is 0. Each press calls setCount(count + 1), increasing count by 1. After two presses, count becomes 2.
Which code snippet correctly creates a React Native Context with a default value and consumes it in a component?
Remember how to call useContext with the context object.
Option D correctly creates a context with default value 'guest' and uses useContext(UserContext) to consume it. Other options misuse useContext or context object.
What error will this React Native code produce when running?
import React, { createContext, useContext } from 'react'; import { Text, View } from 'react-native'; const DataContext = createContext(); function ShowData() { const data = useContext(DataContext); return <Text>{data.message}</Text>; } export default function App() { return ( <View> <ShowData /> </View> ); }
Check what value useContext(DataContext) returns when no Provider is used.
Since DataContext.Provider is not used, useContext(DataContext) returns undefined. Accessing data.message causes a TypeError.
Which is the best explanation for why developers use Context API instead of passing props through many components?
Think about how data is passed in component trees and what problems prop drilling causes.
Context API helps avoid passing props through many layers (prop drilling), making code cleaner and easier to maintain. It does not replace all state management or automatically cache props.