useContext lets you consume context without prop drilling.
Getting Started
What is React?
Components & Props
Components & Props
Performance & Testing
React.memo & Lazy Loading
Custom Hooks
Building Custom Hooks
Error Boundaries
Error Handling
Server Components
React Server Components
Next.js Introduction
Next.js Basics
Animations & Transitions
Framer Motion
React
Intermediate
FREE
useContext Hook
Lesson 3 of 17
Intermediate
Interactive
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.
Interview Questions
It is a fundamental React feature.