@one-view/global-context

OneView Global Context

Usage no npm install needed!

<script type="module">
  import oneViewGlobalContext from 'https://cdn.skypack.dev/@one-view/global-context';
</script>

README

@one-view/global-context

Installation

With NPM

npm install @one-view/global-context

With Yarn

yarn add @one-view/global-context

Usage

Create Context

Create context using useCreateContext hook. This hook will automatically destroy the context when the component unmounted.

import { useCreateContext } from '@one-view/global-context';

const MyComponent = () => {
    useCreateContext('my-namespace');
    ...
}

or create the context manually using createContext helper.

import { createContext } from '@one-view/global-context';

createContext('default', { foo: 'bar' });

Access & Update Context Value

Access and update context inside react component with useGlobalContext hook...

import { useGlobalContext } from '@one-view/global-context';

const MyComponent = () => {
    const { value: foo, update: setFoo } = useGlobalContext<string>('default', 'foo');

    return <button onClick={() => setFoo('baz')}>{foo}</button>;
};

...or anywhere with getContextValue and setContextValue.

import { getContextValue, setContextValue } from '@one-view/global-context';

const foo = getContextValue<string>('default', 'foo');
setContextValue('default', 'foo', 'bar');

Destroy Context

Destroy context with destroyContext helper.

import { destroyContext } from '@one-view/global-context;

destroyContext('default')