Understanding React Context
(Updated on )
Understanding React Context
React Context provides a way to pass data through the component tree without having to pass props manually at every level. In this guide, we’ll explore how to use Context effectively in your React applications.
What is React Context?
Context is 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.
Creating and Using Context
1. Create a Context
const ThemeContext = React.createContext('light');
2. Provide a Context Value
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}
3. Consume the Context
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>Themed Button</button>;
}
Common Use Cases
Theme Switching
const ThemeContext = React.createContext({
theme: 'light',
toggleTheme: () => {}
});
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light');
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
User Authentication
const AuthContext = React.createContext({
user: null,
login: () => {},
logout: () => {}
});
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = (userData) => {
setUser(userData);
};
const logout = () => {
setUser(null);
};
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
Best Practices
- Keep Context focused and specific
- Split Context into smaller pieces
- Use Context for truly global state
- Consider performance implications
Next Steps
- Learn about React Hooks
- Explore React Performance
- Master React Testing
Happy coding!