import React, { createContext, useState, useContext } from 'react';
import { View, Text, Button } from 'react-native';
const UserContext = createContext();
function DeepChild() {
const { userName } = useContext(UserContext);
return (
<View>
<Text>User Name: {userName}</Text>
</View>
);
}
function MiddleChild() {
return <DeepChild />;
}
export default function App() {
const [userName, setUserName] = useState('Alice');
return (
<UserContext.Provider value={{ userName, setUserName }}>
<View style={{ padding: 20 }}>
<Text style={{ fontSize: 20, marginBottom: 10 }}>Global State Demo</Text>
<MiddleChild />
<Button
title="Change Name"
onPress={() => setUserName(userName === 'Alice' ? 'Bob' : 'Alice')}
accessibilityLabel="Change user name button"
/>
</View>
</UserContext.Provider>
);
}We use React's Context API to create a global state called UserContext. The App component holds the userName state and provides it to all child components via UserContext.Provider. The DeepChild component accesses the userName directly from the context using useContext, so it does not need to receive it as a prop from MiddleChild or App. This avoids prop drilling, which means passing props through many layers just to reach a deeply nested component. The button in App changes the global userName, and the change is reflected immediately in DeepChild because it reads from the shared global state.
This approach keeps the code clean and easy to maintain, especially when many components need access to the same data.