Created
November 13, 2020 02:38
-
-
Save davidpaulhunt/8de3be748c434383ef7df6e5c31a1dc8 to your computer and use it in GitHub Desktop.
React Context Example 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
const Ctx = React.createContext({ | |
currency: "USD", | |
format: (val) => val, | |
setCurrency: () => {}, | |
}); | |
Ctx.displayName = "CurrencyCtx"; | |
function CurrencyProvider(props) { | |
const [currency, setCurrency] = React.useState("USD"); | |
const format = React.useCallback( | |
(value) => { | |
return `${value} ${currency}`; | |
}, | |
[currency] | |
); | |
return ( | |
<Ctx.Provider value={{ currency, format, setCurrency }} {...props} /> | |
); | |
} | |
const useCurrency = () => React.useContext(Ctx); | |
export { CurrencyProvider, useCurrency }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment