Skip to content
Home Tutorials Roadmaps Courses Classroom Training Blog
Log in Join free
React Intermediate Free

useContext Hook

Lesson 5 of 17 · State & Lifecycle 29%
1. Getting Started
What is React?
2. Components & Props
Components & Props
6. Performance & Testing
React.memo & Lazy Loading
7. Custom Hooks
Building Custom Hooks
8. State Management
Context API Redux Basics
9. Error Boundaries
Error Handling
10. Server Components
React Server Components
11. Next.js Introduction
Next.js Basics
12. Animations & Transitions
Framer Motion

useContext lets you consume context without prop drilling.

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.

Up next

useReducer Hook

Lesson 6 of 17 · Hooks Advanced