RoduxUtils: Examples

Slices

A problem that I, and many others (from what I’ve witnessed) have had with Rodux is figuring out how to organize it. A common trap some of us fall into is throwing all of your actions into one big folder, and your reducers into another folder. This becomes a big mess at scale, because now everything is mixed together in one big, disorganized pile.

Rodux Utils makes organizing your Rodux code super simple with slices. Just like slices from Redux Toolkit, Rodux Utils’ slices allow you to create feature-specific reducers along with their actions all in one go. It looks something like this:

-- Input/slice.lua

local RoduxUtils = require(ReplicatedStorage.Packages.RoduxUtils)
local Immutable = require(ReplicatedStorage.Shared.Immutable)

local inputSlice = RoduxUtils.createSlice("input", {}, {
    inputProcessed = function(state, action)
        return Immutable.join(state, {
            lastProcessedCommand = action.payload,
        })
    end,
    inputCleared = function(state)
        return Immutable.join(state, {
            lastProcessedCommand = Immutable.none,
        })
    end,
})

This function will do a few things for you.

  1. Create a reducer from the given handlers, just like combineReducers from Rodux.
  2. Create an action creator for each handler.
  3. Store it all in one spot

Accessing your slice’s reducer is super simple.

-- bootstrap.client.lua

local Input = require(ReplicatedStorage.Client.Input)
local Debug = require(ReplicatedStorage.Shared.Debug)

local reducer = Rodux.combineReducers({
    input = Input.slice.reducer,
    debug = Debug.slice.reducer,
})

local store = Rodux.Store.new(reducer)

So is using actions too.

-- processInput.lua

local Input = require(ReplicatedStorage.Client.Input)

local inputProcessed = Input.slice.actions

UserInputService.InputBegan:Connect(function(input, gameProcessed)
    if gameProcessed then
        return
    end
    
    store:dispatch(inputProcessed(input.KeyCode))
end)

This is a real example (although truncated) from a project that I’m currently working on. So far, slices have been really fun to work with and helped keep my code organized.