Context
/ API Reference
Context
/ API Reference

createContext

A convenience helper function to create a context hook and a provider component.
It automatically accepts null as a value to indicate "not set".
The hook will throw an error if you try to use it without a provider.

The Gist

import { createContext } from '@weser/context'

type Theme = 'light' | 'dark'

const [useTheme, ThemeProvider] = createContext<Theme>('light', 'theme')

function App({ children }) {
  return <ThemeProvider value="dark">{children}</ThemeProvider>
}

function Component() {
  const theme = useTheme()

  return (
    <div style={{ backgroundColor: theme === 'dark' ? 'black' : 'white' }}>
      Hello
    </div>
  )
}

Parameters

ParameterTypeDescription
defaultValueT | nullThe default value for when no provider is used.
namestring?A name for the context used in error messages.

Returns

([() => T, ComponentType<ContextProps<T>>]) A tuple where the first element is a hook to use the context and the second element is the context provider component that takes a single value prop.

ContextProps

ParameterTypeDescription
valueTThe value to provide to the context.
On this page