Interview question
What is useContext and how does it solve prop drilling? useContext क्या है और prop drilling को कैसे solve करता है?
Answer
// Create context
const ThemeContext = React.createContext();
// Provider
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Header />
<Main />
</ThemeContext.Provider>
);
}
// Consumer
function DeepComponent() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === 'light' ? 'white' : 'black' }}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
}
// Multiple contexts
const UserContext = React.createContext();
const NotificationContext = React.createContext();useContext से prop drilling solve होता है।
1. Context create करो
2. Provider से wrap करो
3. Deep components में useContext use करोWas this answer clear?