createContextProvider
createContextProvider
is a function that Creates a Provider
component and useProvider
hook with type inference based od provided factory function.
It reduces boilerplate code and makes it easier to use context in your application.
useProvider
hook will throw an error if the context
is undefined
.
useProvider
hook will throw an error if the context
is undefined
.createContextProvider
should be called outside component scope!Example usage
ContextProvider without props
import { createContextProvider } from '@kickass-coderz/react'
const [Provider, useProvider] = createContextProvider(() => {
const [isOpen, setIsOpen] = useState(false)
const toggleOpen = useCallback(() => {
setIsOpen(previous => !previous)
}, [])
return { isOpen, setIsOpen }
})
ContextProvider with props
import { createContextProvider } from '@kickass-coderz/react'
const [Provider, useProvider] = createContextProvider((properties: ProviderProperties) => {
const [isOpen, setIsOpen] = useState(properties.defaultOpen)
const toggleOpen = useCallback(() => {
setIsOpen(previous => !previous)
}, [])
return { isOpen, setIsOpen }
})
ContextProvider with scope and error message
Adding scope
and errorMessage
will make it easier to debug your application.
If scope
is used in Component debeugger you will see NavigationProvider
and NavigationContext
instead of Provider
and Context
. Error message will have scope
prepended to error messages.
errorMessage
will be used in useProvider
hook if context
is undefined
. Combined with scope
it will look like this: [NavigationProvider]: useNavigationProvider must be used within NavigationProvider
.
import { createContextProvider } from '@kickass-coderz/react'
const [NavigationProvider, useNavigationProvider] = createContextProvider(
() => {
const [isOpen, setIsOpen] = useState(false)
const toggleOpen = useCallback(() => {
setIsOpen(previous => !previous)
}, [])
return { isOpen, setIsOpen }
},
{
scope: 'Navigation',
errorMessage: 'useNavigationProvider must be used within NavigationProvider'
}
)