Skip to main content

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:

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:

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:

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:

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.

Explore how to use broadcasters and receivers to sync state:

Server snippet
const broadcaster = createBroadcaster({
producers: slices,
dispatch: (player, actions) => {
remotes.dispatch.fire(player, actions);
},
});
Client snippet
const receiver = createBroadcastReceiver({
start: () => {
remotes.start.fire(0);
},
});