State Management

P5 Svelte provides multiple ways to manage state in your sketches, from local sketch state to global application state using Svelte stores.

Interactive Demo

FPS: 60

State Management Approaches

Local State

State stored directly on the P5 instance.

p5._state = {
  position: { x: 0, y: 0 },
  speed: 5
};

Svelte Stores

Reactive state management using Svelte stores.

const store = writable({
  color: '#ff0000'
});

Props

Configuration passed through component props.

<P5Canvas
  sketch={sketch}
  config={config}
/>

Using Svelte Stores

// stores/sketchState.ts
import { writable } from 'svelte/store';

export const sketchState = writable({
  color: '#ff0000',
  size: 20,
  speed: 1
});

// YourSketch.svelte
const sketch: Sketch = {
  draw: (p5) => {
    sketchState.subscribe(state => {
      p5.fill(state.color);
      p5.circle(x, y, state.size);
    })();
  }
};

Local State Management

Initialization
setup: (p5) => {
  p5._state = {
    entities: [],
    score: 0,
    isActive: true
  };
}
Updates
draw: (p5) => {
  // Update state
  p5._state.entities.forEach(entity => {
    entity.update();
  });

  // Render based on state
  p5._state.entities.forEach(entity => {
    entity.render(p5);
  });
}

Best Practices

Common Pitfalls to Avoid:

  • Modifying state directly in event handlers without proper synchronization
  • Creating new objects every frame instead of updating existing ones
  • Not cleaning up subscriptions when the sketch is destroyed

Next Steps

Learn how to add type safety to your state management with the TypeScript Integration guide.