bookwiz.io / lib / contexts / UsageContext.tsx
UsageContext.tsx
Raw
'use client'

import React, { createContext, useContext, useCallback, useRef } from 'react'

interface UsageContextType {
  refreshUsageStats: () => void
  registerRefreshFunction: (fn: () => void) => void
}

const UsageContext = createContext<UsageContextType>({
  refreshUsageStats: () => {},
  registerRefreshFunction: () => {}
})

export function UsageProvider({ children }: { children: React.ReactNode }) {
  const refreshFunctionRef = useRef<(() => void) | null>(null)

  const refreshUsageStats = useCallback(() => {
    if (refreshFunctionRef.current) {
      refreshFunctionRef.current()
    }
  }, [])

  const registerRefreshFunction = useCallback((fn: () => void) => {
    refreshFunctionRef.current = fn
  }, [])

  return (
    <UsageContext.Provider value={{ refreshUsageStats, registerRefreshFunction }}>
      {children}
    </UsageContext.Provider>
  )
}

export const useUsageRefresh = () => {
  const context = useContext(UsageContext)
  if (!context) {
    throw new Error('useUsageRefresh must be used within a UsageProvider')
  }
  return context
}