Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. import React, { useContext, useState } from 'react'
  2. const MyContext = React.createContext({})
  3.  
  4. const App: React.FC = () => {
  5.  
  6. // Using Provider component under context api for providing
  7. // value to our context
  8. const MyContextProvider = MyContext.Provider
  9.  
  10. // Our Language state with default value 'EN' which is
  11. // also passed down to our context intially
  12. const [lang, setLang] = useState('EN')
  13.  
  14. // Function to change our language state which will automatically
  15. // trigger change in our context value
  16. const changeLang = () => lang === 'EN' ? setLang('FR') : setLang('EN')
  17.  
  18. return (
  19. <>
  20. <h1>React Context API Example With Hooks</h1>
  21. <MyContextProvider value={{lang : lang}}>
  22. {/* ContextConsumer Component encapsulated under context provider */}
  23. <ContextConsumer />
  24. </MyContextProvider>
  25. <button onClick={() => changeLang()}>Change Language</button>
  26. </>
  27. );
  28. }
  29.  
  30.  
  31. const ContextConsumer: React.FC = () => {
  32. // Using useState Hook to consume Context
  33. const context = useContext(MyContext)
  34. return (
  35. <div>
  36. <p>Current Language: {context.lang}</p>
  37. </div>
  38. );
  39. }
  40.  
  41. export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement