useContext lets you consume context without prop drilling.
1. Getting Started
What is React?
2. Components & Props
Components & Props
6. Performance & Testing
React.memo & Lazy Loading
7. Custom Hooks
Building Custom Hooks
9. Error Boundaries
Error Handling
10. Server Components
React Server Components
11. Next.js Introduction
Next.js Basics
12. Animations & Transitions
Framer Motion
Syntax
REACT
import { createContext, useContext } from 'react'; const ThemeContext = createContext("light"); function ThemedButton() { const theme = useContext(ThemeContext); return <button className={theme}>Click me</button>; }
useContext Hook
REACT
import { createContext, useContext, useState } from "react"; const ThemeContext = createContext("light"); function App() { const [theme, setTheme] = useState("dark"); return ( <ThemeContext.Provider value={theme}> <Toolbar /> <button onClick={() => setTheme(t => t === "light" ? "dark" : "light") }>Toggle Theme</button> </ThemeContext.Provider> ); } function Toolbar() { const theme = useContext(ThemeContext); return <p>Current theme: {theme}</p>; }
Practice
1
Exercise
Practice this concept.
Answer
Write the code as shown above.
Quick Quiz
1
What did you learn?
This covers the basics.
Choose an answer to continue.
Interview Questions
It is a fundamental React feature.