Quick Tip — Using Prop() Context in Stencil

Stencil Logo

Another currently hidden jam in Stencil compiler is the Prop() context. In this quick tip post I’ll try to shortly explain what is it and how to use it.


The Prop() Context

In a previous post, I explained how to share state between components in Stencil. In that post I explained how to use the Prop() connect. The Prop() context resembles the Prop() connect in syntax but was created for another purpose. In Stencil there is a CoreContext object which includes various helpful preset properties. Here is it’s current interface:

export interface CoreContext {
addListener?: AddEventListener;
attr?: number;
dom?: DomController;
emit?: (elm: Element, eventName: string, data?: EventEmitterData) => void;
enableListener?: EventListenerEnable;
eventNameFn?: (eventName: string) => string;
isClient?: boolean;
isPrerender?: boolean;
isServer?: boolean;
window?: Window;
location?: Location;
document?: Document;
mode?: string;
[contextId: string]: any;
}

Note: The CoreContext interface might change in the future.

As part of the CoreContext properties you can find flags that will help you to understand if the your component code is running in server mode or client/browser mode. Other CoreContext properties are a reference to the location, document and window objects and more. The context data can be injected to a component using the Prop() context:

@Prop({ context: 'isServer' }) private isServer: boolean;

As you can see in the code, you pass an object to the Prop() decorator with a context member and the member name (from the interface presented previously). Later on, in the component you will be able to use the context data as a regular property of your component:

componentWillLoad() {
if (!this.isServer) {
fetch('http://...').then(...)
}
}

Summary

The Prop() context can be very useful to inject Stencil CoreContext data into your components. This can come handy mainly in server side rendering scenarios but maybe in the future it will be helpful in other scenarios as well.