Context and useContext
Part of the React course
Your app has a dark mode toggle. The toggle lives in the settings panel, but the thing that needs to know about it is a button eight components deep inside a table inside a card inside a page. To get the value from one to the other by props, every single component in between has to accept a theme prop it does not use and hand it straight on.
React has an official escape hatch for this, and the name for it is context: a value published at one point in the component tree that any component underneath can read directly, no matter how deep, without anyone in between passing it along. The image that fits is a radio broadcast. A station transmits on a frequency, and any receiver in range tunes in directly.
Want to learn React Context and useContext in a real environment?
Click below, get a fresh Linux box with React ready to go, and work through Context and useContext hands-on with an AI tutor that knows your code.
Start this lessonContext and useContextWhat you'll learn
- CreateContext
- Context.Provider
- UseContext
- When context is the right tool
- Context vs prop drilling tradeoffs
Read this lesson in your language
All lessons in this course
17 lessons- 1What is React?25 min
- 2JSX and Components30 min
- 3Props30 min
- 4State with useState35 min
- 5Handling Events30 min
- 6Conditional Rendering and Lists30 min
- 7Forms and Controlled Inputs35 min
- 8Effects with useEffect40 min
- 9Data Fetching40 min
- 10Component Composition35 min
- 11Context and useContext35 min
- 12useReducer35 min
- 13Custom Hooks35 min
- 14Performance and Memoization35 min
- 15Routing with React Router40 min
- 16Testing React Components40 min
- 17Capstone: Todo App60 min
