0 day streak
javascript / intermediate
Snippet

Global State Access with Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
const ThemeContext = React.createContext('light');
const Display = () => {
const theme = useContext(ThemeContext);
return <div className={theme}>Current theme: {theme}</div>;
};
const App = () => (
<ThemeContext.Provider value="dark">
<Display />
</ThemeContext.Provider>
);
react
Breakdown
1
useContext(ThemeContext)
Hook that consumes the value from the nearest matching Provider above in the tree.