Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useContext, useState } from 'react'
- const MyContext = React.createContext({})
- const App: React.FC = () => {
- // Using Provider component under context api for providing
- // value to our context
- const MyContextProvider = MyContext.Provider
- // Our Language state with default value 'EN' which is
- // also passed down to our context intially
- const [lang, setLang] = useState('EN')
- // Function to change our language state which will automatically
- // trigger change in our context value
- const changeLang = () => lang === 'EN' ? setLang('FR') : setLang('EN')
- return (
- <>
- <h1>React Context API Example With Hooks</h1>
- <MyContextProvider value={{lang : lang}}>
- {/* ContextConsumer Component encapsulated under context provider */}
- <ContextConsumer />
- </MyContextProvider>
- <button onClick={() => changeLang()}>Change Language</button>
- </>
- );
- }
- const ContextConsumer: React.FC = () => {
- // Using useState Hook to consume Context
- const context = useContext(MyContext)
- return (
- <div>
- <p>Current Language: {context.lang}</p>
- </div>
- );
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement