Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials React useContext Hook
React Intermediate FREE

useContext Hook

Lesson 3 of 17 Intermediate Interactive

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.

Interview Questions

It is a fundamental React feature.