share-page-context.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use client'
  2. import { useCallback, useEffect, useState } from 'react'
  3. import { createContext, useContextSelector } from 'use-context-selector'
  4. import type { FC, ReactNode } from 'react'
  5. import { Theme } from '@/types/app'
  6. export type SharePageContextValue = {
  7. theme: Theme
  8. setTheme: (theme: Theme) => void
  9. }
  10. const SharePageContext = createContext<SharePageContextValue>({
  11. theme: Theme.light,
  12. setTheme: () => { },
  13. })
  14. export function useSelector<T>(selector: (value: SharePageContextValue) => T): T {
  15. return useContextSelector(SharePageContext, selector)
  16. }
  17. export type SharePageContextProviderProps = {
  18. children: ReactNode
  19. }
  20. export const SharePageContextProvider: FC<SharePageContextProviderProps> = ({ children }) => {
  21. const [theme, setTheme] = useState<Theme>(Theme.light)
  22. const handleSetTheme = useCallback((theme: Theme) => {
  23. setTheme(theme)
  24. globalThis.document.documentElement.setAttribute('data-theme', theme)
  25. }, [])
  26. useEffect(() => {
  27. globalThis.document.documentElement.setAttribute('data-theme', theme)
  28. // eslint-disable-next-line react-hooks/exhaustive-deps
  29. }, [])
  30. return (
  31. <SharePageContext.Provider value={{
  32. theme,
  33. setTheme: handleSetTheme,
  34. }}>
  35. {children}
  36. </SharePageContext.Provider>
  37. )
  38. }
  39. export default SharePageContextProvider