From 454f44e7c00594fe45475536455bfaab184d8feb Mon Sep 17 00:00:00 2001 From: Jimmy Cleveland Date: Wed, 9 Oct 2019 22:25:15 -0600 Subject: [PATCH] Add usage example for useContext. (#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. --- content/docs/hooks-reference.md | 44 +++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/content/docs/hooks-reference.md b/content/docs/hooks-reference.md index 41464b47..852ae483 100644 --- a/content/docs/hooks-reference.md +++ b/content/docs/hooks-reference.md @@ -196,6 +196,50 @@ A component calling `useContext` will always re-render when the context value ch > >`useContext(MyContext)` only lets you *read* the context and subscribe to its changes. You still need a `` above in the tree to *provide* the value for this context. +**Putting it together with Context.Provider** +```js{31-36} +const themes = { + light: { + foreground: "#000000", + background: "#eeeeee" + }, + dark: { + foreground: "#ffffff", + background: "#222222" + } +}; + +const ThemeContext = React.createContext(themes.light); + +function App() { + return ( + + + + ); +} + +function Toolbar(props) { + return ( +
+ +
+ ); +} + +function ThemedButton() { + const theme = useContext(ThemeContext); + + return ( + + ); +} +``` +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. + + ## Additional Hooks {#additional-hooks} 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.