Skip to main content
Context provides a way to pass data through the component tree without having to pass props down manually at every level. It’s designed to share data that can be considered “global” for a tree of Preact components.

When to Use Context

Context is ideal for sharing data that is needed by many components at different nesting levels:
  • Current authenticated user
  • Theme preferences (dark/light mode)
  • Language/locale settings
  • UI state (modals, notifications)
Don’t use Context just to avoid passing props a few levels down. Context makes component reuse more difficult.

Creating Context

Use createContext to create a new context object. It accepts a default value that’s used when a component doesn’t have a matching Provider above it.

Implementation Details

The createContext function is implemented in src/create-context.js. It returns a special component that acts as both Provider and Consumer:
Reference: src/create-context.js:6-60

Provider Component

Every Context object comes with a Provider component that allows consuming components to subscribe to context changes.

Consuming Context

There are two ways to consume context in Preact:

Practical Examples

Best Practices

Performance Considerations

Context updates cause all consuming components to re-render. Here are strategies to optimize:
Split frequently changing values into separate contexts:
Now components that only need theme won’t re-render when user changes.

Next Steps

Hooks

Learn more about hooks including useContext

Refs

Work with DOM references and forward refs