useAssets

useAssets provides synchronous access to preloaded assets from the AssetManager cache. Assets must be preloaded via AssetLoader before accessing them.

tsx
import { useAssets } from "@carverjs/core/hooks";

Quick Start #

tsx
import { useAssets } from "@carverjs/core/hooks";

function GameConfig() {
  const config = useAssets<{ speed: number; gravity: number }>("/data/config.json");

  return <p>Player speed: {config.speed}</p>;
}

Single Asset #

tsx
const levelData = useAssets<LevelData>("/maps/level-1.json");

Returns the cached asset data. Throws if the asset is not found in the cache.


Multiple Assets #

tsx
const [config, tilemap] = useAssets<[GameConfig, TilemapData]>([
  "/data/config.json",
  "/maps/level-1.json",
]);

Returns an array of cached assets in the same order as the keys. Throws if any asset is missing.


Reference Counting #

useAssets automatically retains assets on mount and releases them on unmount. While a component is mounted and using an asset, that asset is protected from LRU cache eviction — even under memory pressure.

tsx
function Level1() {
  // This asset won't be evicted while Level1 is mounted
  const map = useAssets<MapData>("/maps/level-1.json");
  return <RenderMap data={map} />;
}

Usage with AssetLoader #

The typical pattern is to preload assets via AssetLoader and access them via useAssets:

tsx
import { Game, World, AssetLoader } from "@carverjs/core/components";
import { useAssets } from "@carverjs/core/hooks";

const manifest = [
  { url: "/data/config.json" },
  { url: "/data/enemies.json" },
];

function GameWorld() {
  const config = useAssets<GameConfig>("/data/config.json");
  const enemies = useAssets<EnemyDef[]>("/data/enemies.json");

  return (
    <World>
      {enemies.map((e) => (
        <Enemy key={e.id} data={e} speed={config.enemySpeed} />
      ))}
    </World>
  );
}

function App() {
  return (
    <Game>
      <AssetLoader manifest={manifest} fallback={<p>Loading...</p>}>
        <GameWorld />
      </AssetLoader>
    </Game>
  );
}

Type Definitions #

See Types for AssetType, AssetEntry, and LoadingProgress.