use_context

You can simplify passing props through your component tree by using the use_context hook to share values. This hook allows you to access the current value of a Context, which tracks the latest value provided by its closest provider.

Tip

use_context and Context are based on React’s Context API. See the React docs for more in-depth explanations and examples.

Example

Note

These examples are simplified for clarity. Generally, context is best suited for components with significantly more nested layers.

Nesting providers

Providers can be nested. The nearest provider in the tree supplies the value as inner providers override outer ones.

Multiple contexts

Multiple independent contexts can be provided simultaneously on the same component tree.

Default value

If use_context is called outside any provider, it returns the default value passed to Context().

Recommendations

  1. Prefer context to avoid prop drilling: If you are passing the same prop through many levels of components that don’t use it, consider using context.
  2. One context per concern: Keep each Context object focused on a single value. Bundling many unrelated values into one context means all consumers re-render whenever any part changes.
  3. Provide close to the root: Wrap the smallest subtree that actually needs the value. This keeps the scope of the provided value explicit.