Skip to content

Commit 454f44e

Browse files
Jimmydaleclevelandalexkrolick
authored andcommitted
Add usage example for useContext. (reactjs#2414)
* Add usage example for useContext. The intent is to show where the hook fits in to the usual Context usage. * Remove unnecessary comment in code block.
1 parent 0726327 commit 454f44e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

content/docs/hooks-reference.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,50 @@ A component calling `useContext` will always re-render when the context value ch
196196
>
197197
>`useContext(MyContext)` only lets you *read* the context and subscribe to its changes. You still need a `<MyContext.Provider>` above in the tree to *provide* the value for this context.
198198
199+
**Putting it together with Context.Provider**
200+
```js{31-36}
201+
const themes = {
202+
light: {
203+
foreground: "#000000",
204+
background: "#eeeeee"
205+
},
206+
dark: {
207+
foreground: "#ffffff",
208+
background: "#222222"
209+
}
210+
};
211+
212+
const ThemeContext = React.createContext(themes.light);
213+
214+
function App() {
215+
return (
216+
<ThemeContext.Provider value={themes.dark}>
217+
<Toolbar />
218+
</ThemeContext.Provider>
219+
);
220+
}
221+
222+
function Toolbar(props) {
223+
return (
224+
<div>
225+
<ThemedButton />
226+
</div>
227+
);
228+
}
229+
230+
function ThemedButton() {
231+
const theme = useContext(ThemeContext);
232+
233+
return (
234+
<button style={{ background: theme.background, color: theme.foreground }}>
235+
I am styled by theme context!
236+
</button>
237+
);
238+
}
239+
```
240+
This example is modified for hooks from a previous example in the [Context Advanced Guide](/docs/context.html), where you can find more information about when and how to use Context.
241+
242+
199243
## Additional Hooks {#additional-hooks}
200244

201245
The following Hooks are either variants of the basic ones from the previous section, or only needed for specific edge cases. Don't stress about learning them up front.

0 commit comments

Comments
 (0)