Component Context

CKComponentContext

Provides a way to pass data through the component tree without having to pass props down manually at every level. Items are keyed by class.

In ComponentKit, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Component context provides a way to implicitly share values like these between components without having to explicitly pass a prop through every level of the tree.

CKComponentContext values are NOT expected to change between component generations. This is an optimization to allow better component reuse in CKRenderComponent. If your context values need to be changed between component generations, take a look at CKComponentMutableContext.

Context should be used sparingly. Prefer explicitly passing parameters instead.

Example usage:

{
// Declaring a context:
CKComponentContext<CKFoo> c(foo);
// Reading a context: (any components created while c is in scope will be able to read its value by calling).
auto const foo = CKComponentContext<CKFoo>::get();
}

You may nest contexts with the same class, in which case the innermost context defines the value when fetched:

{
CKComponentContext<CKFoo> c1(foo1);
{
CKComponentContext<CKFoo> c2(foo2);
// CKComponentContext<CKFoo>::get() will return foo2 here
}
// CKComponentContext<CKFoo>::get() will return foo1 here
}

CKComponentMutableContext

Similar to CKComponentContext, but allows context values changes between generations.

Example usage:

{
// Declaring a context:
CKComponentMutableContext<CKFoo> c(foo);
// Reading a context: (any components created while c is in scope will be able to read its value by calling).
auto const foo = CKComponentMutableContext<CKFoo>::get();
}

You may nest contexts with the same class, in which case the innermost context defines the value when fetched:

{
CKComponentMutableContext<CKFoo> c1(foo1);
{
CKComponentMutableContext<CKFoo> c2(foo2);
// CKComponentMutableContext<CKFoo>::get() will return foo2 here
}
// CKComponentMutableContext<CKFoo>::get() will return foo1 here
}

If you have to use context, consider using CKComponentContext instead. CKComponentMutableContext makes component reuse more difficult.