Context

@mvuijs/core / rx / Context

Context<T> #

Contexts are a way that components can share state (or any arbitrary object really) that is local to a component and all its arbitrarily deeply nested children. In that sense they differ from both global and component local state.

For simple use-cases, it is preferable to use events and state bindings. There are situations though where more powerful state sharing is desirable.

See also getContext and provideContext .

Example #

const myCtx = new rx.Context(() => new rx.State(0));

@Component.register
class CtxProvider extends Component {
  render() {
    const ctx = this.provideContext(myCtx);
    return [
      h.div(ctx.derive(v => 'Value in Provider: ')),
      h.slot(),
    ]
  }
}

@Component.register
class CtxConsumer extends Component {
  props = { value: rx.prop<string>() }

  render() {
    const ctx = this.getContext(myCtx);
    return [
      h.button({ events: { click: _ => ctx.next(this.props.value) }}),
    ]
  }
}

class Main extends Component {
  render() {
    return [
      CtxProvider.t([
        CtxConsumer.t({ props: { value: 'val1' }),
        CtxConsumer.t({ props: { value: 'val2' }),
      ])
    ]
  }
}

// when clicking one of the consumers, the value in the provider will update

In Other Frameworks #

Contexts exist in pretty much all modern frontend frameworks in one way or another. React, Solid and Svelte all have them, lit-element is experimenting with them and even though angular has no contexts specifically, it can still share state with nested child components via “sandboxing” .

Type parameters #

  • T

Constructors #

constructor() #

Signature #

new Context<T>(generateInitialValue?: Function): Context<T>;

Type parameters #

  • T

Parameters #

Name Type
generateInitialValue? () => T

Returns #

Context <T>

Defined in: packages/core/src/rx/context.ts:67

Properties #

generateInitialValue? #

Function

Type declaration #

Signature #
(): T;
Returns #

T

Defined in: packages/core/src/rx/context.ts:67