Skip to content

Basic Usage

Phaser Hooks provides two fundamental state types:

Local state is scene-specific and automatically cleaned up when the scene is destroyed.

import { withLocalState } from 'phaser-hooks';
export class GameScene extends Phaser.Scene {
create() {
// Local state only exists while this scene is active
const playerState = withLocalState(this, 'player', {
hp: 100,
mp: 50,
level: 1,
});
console.log('Player HP:', playerState.get().hp);
}
}

Best for:

  • Player stats that reset between scenes
  • UI state specific to a scene
  • Temporary game state

Global state persists across all scenes until explicitly cleared.

import { withGlobalState } from 'phaser-hooks';
export class GameScene extends Phaser.Scene {
create() {
// Global state persists across scene transitions
const gameSettings = withGlobalState(this, 'settings', {
soundVolume: 0.8,
musicVolume: 0.6,
difficulty: 'normal',
});
console.log('Sound Volume:', gameSettings.get().soundVolume);
}
}

Best for:

  • Game settings that persist across scenes
  • Global player progress
  • Application-wide configuration

Use the .get() method to retrieve the current state value:

const playerState = withLocalState(this, 'player', { hp: 100, level: 1 });
const currentPlayer = playerState.get();
console.log('HP:', currentPlayer.hp); // 100
console.log('Level:', currentPlayer.level); // 1

Use the .set() method to update state:

const playerState = withLocalState(this, 'player', { hp: 100, level: 1 });
// Update state
playerState.set({
hp: 90,
level: 1,
});
// Or use spread operator to update partially
playerState.set({
...playerState.get(),
hp: playerState.get().hp - 10,
});

Subscribe to state changes using the .on() method:

const playerState = withLocalState(this, 'player', { hp: 100 });
// Listen to changes
const unsubscribe = playerState.on('change', (newPlayer, oldPlayer) => {
console.log('HP changed from', oldPlayer.hp, 'to', newPlayer.hp);
if (newPlayer.hp <= 0) {
console.log('Game Over!');
}
});
// Later, unsubscribe
unsubscribe();