@sirse-dev/safe-context
TypeScript icon, indicating that this package has built-in type declarations

0.3.0 • Public • Published

@sirse-dev/safe-context

Safe React context

npm version npm downloads vulnerabilities

Why?

React requires default value for the context. However, in some cases, default value doesn't have any meaning, because consumers cannot exist outside Provider. SafeContext lets you to have context, that could be used only inside provider. Trying to use Consumer or useSafeContext outside Provider will result in runtime error.

Install

npm install @sirse-dev/safe-context

Or

yarn add @sirse-dev/safe-context

Usage

import { createSafeContext, useSafeContext } from '@sirse-dev/safe-context';

//     This should be non-nullable type ↓      ↓ - no default value.
const SampleContext = createSafeContext<number>();

// Use it as standard context.
const App = () => {
    return (
        <SampleContext.Provider value={10}>
            {/* Some app code... */}

            <SampleContext.Consumer>{(value) => <p>{value}</p>}</SampleContext.Consumer>
            <InnerComponent />
        </SampleContext.Provider>
    );
};

// Or from hook api
const InnerComponent = () => {
    const value = useSafeContext(SampleContext);

    return <div>{value}</div>;
};

License

MIT © sirse

Created with aqu 🌊

Readme

Keywords

none

Package Sidebar

Install

npm i @sirse-dev/safe-context

Weekly Downloads

86

Version

0.3.0

License

MIT

Unpacked Size

17.5 kB

Total Files

11

Last publish

Collaborators

  • sirse