Basic Usage
Understanding State Types
Section titled “Understanding State Types”Phaser Hooks provides two fundamental state types:
Local State
Section titled “Local State”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
Section titled “Global 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
Working with State
Section titled “Working with State”Getting Values
Section titled “Getting Values”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); // 100console.log('Level:', currentPlayer.level); // 1Setting Values
Section titled “Setting Values”Use the .set() method to update state:
const playerState = withLocalState(this, 'player', { hp: 100, level: 1 });
// Update stateplayerState.set({ hp: 90, level: 1,});
// Or use spread operator to update partiallyplayerState.set({ ...playerState.get(), hp: playerState.get().hp - 10,});Listening to Changes
Section titled “Listening to Changes”Subscribe to state changes using the .on() method:
const playerState = withLocalState(this, 'player', { hp: 100 });
// Listen to changesconst 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, unsubscribeunsubscribe();Next Steps
Section titled “Next Steps”- Local State - Deep dive into scene-specific state
- Global State - Learn about persistent cross-scene state
- Event Management - Learn about unsubscribing and cleanup
- Advanced Usage - Explore computed state, undo/redo, and more
- Validation - Add validation to your state