Context
A React feature that provides a way to pass data through the component tree without having to pass props down manually at every level.
Overview
Context provides a way to share values between components without explicitly passing props through every level of the tree. It's designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language.
Example
javascriptimport { createContext, useContext, useState } from 'react'; // Create context const ThemeContext = createContext('light'); // Provider component function App() { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={{ theme, setTheme }}> <Toolbar /> </ThemeContext.Provider> ); } // Consumer component (using useContext hook) function ThemedButton() { const { theme, setTheme } = useContext(ThemeContext); return ( <button style={{ background: theme === 'dark' ? '#333' : '#fff', color: theme === 'dark' ? '#fff' : '#000' }} onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')} > Toggle Theme </button> ); }
Key Points
- Avoids prop drilling
- Created with createContext()
- Accessed with useContext() hook
- Provider passes value down tree
- Common uses: theme, auth, language
Learn More
- Hooks - React Hooks
- Props - Component props
- State - Component state
- React Docs: Context