Reflex
Reflex allow you to efficiently track and manage the state of your game. This page documents the core Reflex APIs.
Reflex provides these top-level exports:
createProducer(initialState, actions)
combineProducers(producers)
createSelector(dependencies, combiner)
createBroadcaster(options)
createBroadcastReceiver(options)
loggerMiddleware
See the source code on GitHub →
Producers
Producers are the state containers that control the state of your game. They are the core of Reflex and are used to listen to state changes and dispatch actions.
Explore how to use producers to manage your game:
createProducer
creates a producer with an initial state and a set of actions.- Producers contain your state, actions, and everything you need to manage them.
combineProducers
lets you compose a new producer of multiple slices.
const producer = createProducer(0, {
increment: (state, value: number) => state + value,
decrement: (state, value: number) => state - value,
set: (_, value: number) => value,
});
Selectors
If your state is a complex object, you can use selectors to extract specific parts of it. Selectors are functions that take your state and return a subset of it. Reflex offers a built-in function to write efficient selectors:
createSelector
optimizes selectors to only run when state changes.
const selectItems = (state: State) => state.items;
const selectInStock = createSelector(selectItems, (items) => {
return items.filter((item) => item.stock > 0);
});
Middleware
Middleware lets you enhance actions and producers with additional functionality. You can use middleware to add logging, patch methods, cancel actions, and more.
Reflex provides some commonly used middleware:
loggerMiddleware
logs all actions and state changes.
You can also define your own middleware:
producer.applyMiddleware(loggerMiddleware, customMiddleware);
Server-to-client sync
Reflex offers a built-in solution to sync state between the server and the client with broadcasters and receivers. They assist the server with separating private and shared state, and they help the client with syncing state with the server.
createBroadcaster
creates a broadcaster that shares server state with clients.createBroadcastReceiver
creates a receiver that syncs client state with the server.
Explore how to use broadcasters and receivers to sync state:
const broadcaster = createBroadcaster({
producers: slices,
dispatch: (player, actions) => {
remotes.dispatch.fire(player, actions);
},
});
const receiver = createBroadcastReceiver({
start: () => {
remotes.start.fire(0);
},
});