javascript / intermediate
Snippet
Sharing State with Context API
The Context API provides a way to pass data through the component tree without having to manually pass props down through every level (prop drilling).
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const ThemeContext = React.createContext('light');function App() {return (<ThemeContext.Provider value="dark"><Layout /></ThemeContext.Provider>);}function Layout() {const theme = React.useContext(ThemeContext);return <div className={`theme-${theme}`}>The current theme is {theme}</div>;}
react
Breakdown
1
React.createContext('light')
Initializes a context object with a default value of 'light'.
2
ThemeContext.Provider value="dark"
Provides the value 'dark' to all descendants in the component tree.
3
React.useContext(ThemeContext)
Consumes the current value from the nearest matching Provider above in the tree.