threlte logo
Basics

Context

Svelte’s Context is a way to pass data through the component tree without having to pass props down manually at every level.

The recommended app structure is to implement the component <Canvas> that provides all basic contexts and use a single child component (typically named “Scene.svelte” in examples) for your Threlte app. This way, you don’t need to worry about the presence of contexts in your components.

App.svelte
<script>
  import { Canvas } from '@threlte/core'
  import Scene from './Scene.svelte'
</script>

<Canvas>
  <Scene />
</Canvas>
Scene.svelte
<script>
  import { T, useFrame } from '@threlte/core'
  import { interactivity } from '@threlte/extras'
  import Player from './Player.svelte'
  import World from './World.svelte'

  let rotation = 0

  // useFrame is relying on a context provided
  // by <Canvas>. Because we are definitely inside
  // <Canvas>, we can safely use it.
  useFrame((_, delta) => {
    rotation += delta
  })

  // This file is also typically the place to
  // inject plugins
  interactivity()
</script>

<T.Mesh rotation.y={rotation}>
  <T.BoxGeometry />
  <T.MeshBasicMaterial color="red" />
</T.Mesh>

<Player />
<World />