Skip to content

Basic Pattern

The fundamental pattern for creating custom hooks.

hooks/withPlayer.ts
import { withLocalState } from 'phaser-hooks';
export function withPlayer(scene: Phaser.Scene) {
return withLocalState(scene, 'player', {
hp: 100,
level: 1
});
}

That’s it! Now use anywhere:

const player = withPlayer(this);
player.get(); // { hp: 100, level: 1 }
import { type HookState, withLocalState } from 'phaser-hooks';
type Player = {
hp: number;
maxHp: number;
level: number;
};
export function withPlayer(scene: Phaser.Scene): HookState<Player> {
return withLocalState<Player>(scene, 'player', {
hp: 100,
maxHp: 100,
level: 1
});
}
export function withSettings(scene: Phaser.Scene) {
return withGlobalState(scene, 'settings', {
volume: 0.8,
difficulty: 'normal'
});
}
export function withGameProgress(scene: Phaser.Scene) {
return withPersistentState(
scene,
'progress',
{ level: 1, score: 0 },
'my-game-progress',
'local'
);
}

Use “with” prefix (consistent with library) ✅ Describe what it manages (withPlayer, withSettings) ✅ Singular form (withEnemy, not withEnemies)

// ✅ Good names
withPlayer
withSettings
withInventory
withGameState
// ❌ Avoid
usePlayer // Conflicts with ESLint
playerHook // Not descriptive
getPlayer // Sounds like a getter, not a hook
src/
├── hooks/
│ ├── withPlayer.ts
│ ├── withSettings.ts
│ ├── withInventory.ts
│ └── index.ts ← Export all hooks
├── scenes/
│ └── GameScene.ts
└── ...
hooks/index.ts
export { withPlayer } from './withPlayer';
export { withSettings } from './withSettings';
export { withInventory } from './withInventory';
// Usage in scenes
import { withPlayer, withSettings } from '@/hooks';