Other Utilities
$render Context

$render Context

$render context is used to create and access the specific global state of a component. $render context is used to make the data of a component accessible to other components without passing them down as props.

$render context is all about using createContext() and useContext(). It is very similar to React context but with some twists.

To use createContext() or useContext(), you need to setup the $state() utility. Click $state() (opens in a new tab) to set it up.

Once you setup the $state() utility, then you can use createContext() and useContext().

When do you need $render Conext?

You need $render Context when many deeply nested children components need props from their parents and you don't want to pass down the props. Then, $render Context is important. Unlike React Context, you can make $render Context consumers independent of the context.

createContext()

It creates a specific global state for a component. The specific global state is only accessible by the component it is created for.

createContext(Component, data);

createContext() takes two parameters, Component and data. In short, the data is attached to the context of the Component provided.

createContext(Player, appState);

Now, the appState can be consumed through the Player component by using useContext().

useContext()

It is used to consumed data from the global context of a component.

useContext(Component);

useContext() takes a component from which data will be consumed. If no context data has been created for the component provided, undefined will be returned.

//Player is a component
const appState = useContext(Player);
  • Make components independent of the context they consume

You can make components independent of the context they consume by making them optionally dependent on the context.

const componentState = props ? props : useContext(Player);

Or

const componentState = props ?? useContext(Player);

Now, we are able to get the data attached to the global context of the Player component and even make the components that consume the context independent of it.