Guest User

React Context

a guest
Jun 26th, 2021
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // context
  2. import {
  3.   createContext,
  4.   Dispatch,
  5.   SetStateAction
  6. } from "react";
  7.  
  8. type State<T> = [
  9.   T,
  10.   Dispatch<SetStateAction<T>>
  11. ];
  12.  
  13. type InitValue = {
  14.   isDarkTheme: boolean
  15. }
  16.  
  17. type ContextType = {
  18.   isDarkThemeState: State<boolean>
  19. }
  20.  
  21. export const initValue: InitValue = {
  22.     isDarkTheme: window.localStorage.getItem("isDarkTheme") === "true"
  23.     ? true
  24.     : window.matchMedia &&
  25.         window.matchMedia("(prefers-color-scheme: dark)").matches,
  26. }
  27.  
  28. const globalContext = createContext(
  29.   (initValue as unknown) as ContextType
  30. );
  31.  
  32. export const GlobalContextProvider = globalContext.Provider;
  33.  
  34. export default globalContext;
  35. // App Provider
  36. import { useState, ReactNode } from "react";
  37.  
  38. interface AppProviderProperties {
  39.   children: ReactNode;
  40. }
  41.  
  42. const { isDarkTheme } = initValue;
  43.  
  44. const AppProvider = ({ children }: AppProviderProperties): JSX.Element => {
  45.   const isDarkThemeState = useState(isDarkTheme);
  46.   return (
  47.     <GlobalContextProvider value={{
  48.       isDarkThemeState,
  49.     }}>{children}</GlobalContextProvider>
  50.   );
  51. }
  52.  
  53. export default AppProvider;
  54. // Nested components
  55. import { useContext } from "react";
  56.  
  57. const Example = (): JSX.Element => {
  58.   const { isDarkThemeState } = useContext(globalContext);
  59.   const [isDarkTheme, setIsDarkTheme] = isDarkThemeState;
  60.   return <></>;
  61. }
  62.  
  63. export default Example;
Advertisement
Add Comment
Please, Sign In to add comment