mihomo-party-org/clash-party · error · Error

useRules must be used within an RulesProvider

Error message

useRules must be used within an RulesProvider

What it means

useRules consumes the Rules context (rules list plus a mutate function) and throws when no RulesProvider is present above the caller. The context defaults to undefined, and the hook converts that into an explicit error so the misuse is caught at the call site.

Source

Thrown at src/renderer/src/hooks/use-rules.tsx:34

  })

  React.useEffect(() => {
    const handler = (): void => {
      mutate()
    }
    window.electron.ipcRenderer.on('rulesUpdated', handler)
    return (): void => {
      window.electron.ipcRenderer.removeListener('rulesUpdated', handler)
    }
  }, [mutate])

  return <RulesContext.Provider value={{ rules, mutate }}>{children}</RulesContext.Provider>
}

export const useRules = (): RulesContextType => {
  const context = useContext(RulesContext)
  if (context === undefined) {
    throw new Error('useRules must be used within an RulesProvider')
  }
  return context
}

View on GitHub (pinned to 911e090537)

Solutions

  1. Wrap consumers with <RulesProvider> (or move the provider up above the router/app root).
  2. Ensure the provider stays mounted whenever consumers can render (guard consumers on the same condition as the provider).
  3. In tests, supply RulesProvider (or a stub context provider) via the render wrapper option.
  4. If a component must work with or without rules, accept rules via props instead of the hook at that level.

Example fix

// before
function RulesTable() {
  const { rules, mutate } = useRules()
  return <table>{rules.map(...)}</table>
}
// after
<RulesProvider>
  <RulesTable />
</RulesProvider>
Defensive patterns

Strategy: validation

Validate before calling

const context = React.useContext(RulesContext)
if (context === undefined) {
  return <RulesUnavailable />
}

Type guard

function hasRulesContext(c: RulesContextType | undefined): c is RulesContextType {
  return c !== undefined
}

Prevention

When it happens

Trigger: Calling useRules() from a component not nested under <RulesContext.Provider> (rendered by RulesProvider); calling it from outside React render (event handlers registered at module scope, plain utility functions); rendering consumers in a detached React root such as tests.

Common situations: Provider placed inside a layout that some routes skip; consumers rendered in portals or dialogs attached to document.body but created from outside the tree; forgetting the wrapper in unit tests after extracting a component.

Related errors


AI-assisted analysis of mihomo-party-org/clash-party@911e090537 (2026-08-30). Data as JSON: /api/errors/fef286f952ad539c. Report an issue: GitHub.