Skip to content

Instantly share code, notes, and snippets.

@JulianG
Created August 9, 2020 14:07
Show Gist options
  • Save JulianG/9aa3e0d299e0eb35637cd9d69540d4f9 to your computer and use it in GitHub Desktop.
Save JulianG/9aa3e0d299e0eb35637cd9d69540d4f9 to your computer and use it in GitHub Desktop.
Create React Strict Context
import React from 'react';
export function createStrictContext(options = {}) {
const Context = React.createContext(undefined);
Context.displayName = options.name;
function useContext() {
const context = React.useContext(Context);
if (!context) {
throw new Error(options.errorMessage || `${name || ''} Context Provider is missing`);
}
return context;
}
return [Context.Provider, useContext];
}
import React from 'react'
export function createStrictContext<T>(
options: {
errorMessage?: string
name?: string
} = {}
) {
const Context = React.createContext<T | undefined>(undefined)
Context.displayName = options.name
function useContext() {
const context = React.useContext(Context)
if (!context) {
throw new Error(options.errorMessage || `${name || ''} Context Provider is missing`)
}
return context
}
return [Context.Provider, useContext] as [React.Provider<T>, () => T]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment