one-hook
Size
0.14 kb
View source

useInvariantContext

useContext that throws if the provider is not found.

Installation

npm install @1hook/use-invariant-context

Usage

import {  } from '@1hook/use-invariant-context'

An error is thrown if the context value is falsy.

const  = ()

// optionally pass a custom error message

const  = (, 'Context not found')

Example

This example shows how to use useInvariantContext to avoid missing context provider.

const  = < | null>(null)

type  = { : ; :  }

export function ({ ,  }: ) {
  return (
    <. ={}>{}</.>
  )
}

// ❌ returns `Value | null` since there is not garantee that the context provider is present
export const  = () => ()

// ✅ returns `Value` or throws an error if the context provider is not found
export const  = () => ()

On this page