threlte logo
@threlte/core

Plugins

Plugins are one of Threlte’s superpowers. Plugins allow you to globally extend Threlte’s <T> component functionality. This means you can not only add arbitrary props and event handlers to your <T> components but also override the default behavior of the <T> component entirely.

Plugins add code to every <T> component instance. That code acts as if it were part of the <T> component itself. You have full access to props, event listeners and the component instance itself. For an advanced example of what a plugin can do, see the interactivity plugin of @threlte/extras.

If you want to learn more about authoring plugins, see the plugins section of the learn guide.

injectPlugin

The function injectPlugin adds a plugin to all descendant <T> components of the component that invokes it. This means that you can add plugins to a specific part of your scene graph without affecting the rest of the scene graph.

import { injectPlugin } from '@threlte/core'

injectPlugin('plugin-name', (args) => {
  // We are *inside* a `<T>` component instance

  // args is reactive and holds a reference to `ref`,
  // `makeDefault`, `args`, `attach`, `manual`,
  // `makeDefault`, `dispose` and all other props
  // declared on the `<T>` component.

  // Use effects to react to changes in args
  $effect(() => {
    console.log(args.ref)
  })

  // Use lifecycle functions
  onMount(() => {
    console.log('mounted')
  })

  return {
    // These props are reserved for this plugin, the
    // `<T>` component instance will not act on them.
    pluginProps: ['plugin-prop-a', 'plugin-prop-b']
  }
})

You may also override a plugin namespace further down the tree by calling injectPlugin again with the same plugin name.

injectPlugin is relying on a context provided by your root <Canvas> component and can therefore only be used inside a <Canvas> component.