Skip to content

Commit

Permalink
✨ Add ResponsivenessContext and useResponsiveness hook ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
Aszurar committed Jan 16, 2024
1 parent cb2de90 commit f08eba2
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/context/responsiveness/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import React, { createContext, useEffect, useMemo, useState } from 'react'

interface ResponsivenessContextProps {
isMobile: boolean
}

interface ResponsivenessProviderProps {
children: React.ReactNode
}

const ResponsivenessContext = createContext({} as ResponsivenessContextProps)

function ResponsivenessProvider({
children,
}: Readonly<ResponsivenessProviderProps>) {
const [currentBrowserWidth, setCurrentBrowserWidth] = useState(0)
const isMobile = currentBrowserWidth < 640

function onUpdateCurrentBrowserWidth() {
setCurrentBrowserWidth(window.innerWidth)
}

useEffect(() => {
window.addEventListener('resize', onUpdateCurrentBrowserWidth)
return () => {
window.removeEventListener('resize', onUpdateCurrentBrowserWidth)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

const contextValue = useMemo(() => ({ isMobile }), [isMobile])

return (
<ResponsivenessContext.Provider value={contextValue}>
{children}
</ResponsivenessContext.Provider>
)
}

export { ResponsivenessProvider, ResponsivenessContext }
13 changes: 13 additions & 0 deletions src/hook/useResponsiveness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useContext } from 'react'
import { ResponsivenessContext } from '../context/responsiveness'

export function useResponsiveness() {
const context = useContext(ResponsivenessContext)

if (!context) {
throw new Error(
'useResponsiveness must be used within a ResponsivenessProvider',
)
}
return context
}

0 comments on commit f08eba2

Please sign in to comment.