Can't wrap my head around React-lua contexts

I’ve gone through, jsdotlua.github.io/react-lua, How To: React + Roblox, using Roact and ThemeContext in roblox studio, and even the react docs react.dev/reference/react/useContext and tutorials on youtube (but I personally find it difficult to translate these into lua code.)

I still cannot comprehend how to use and pass context! There’s a code block in the ‘Migrating From Legacy Roact’ section from jsdotlua that makes some sense,

local AppStyle = require(script.Parent.AppStyle)

local StyleContext = Roact.createContext(nil)

local Label = Roact.Component:extend("Label")

function Label:render()
    return Roact.createElement(StyleContext.Consumer, {
        render = function(style)
            return Roact.createElement("TextLabel", {
                BackgroundColor3 = style.LabelColor,
                Text = props.text,
            })
        end
    })
end

local App = Roact.Component:extend("App")

function App:render()
    return Roact.createElement(StyleContext.Provider, {
        value = AppStyle,
    }, {
        App = Roact.createElement("Frame", {
            Size = UDim2.fromScale(1, 1)
        }, {
            Start = Roact.createElement(Button, {
                text = "Hello World",
            })
        })
    })
end

I’m aware it says Roact, that’s how it is on jsdotlua

But there’s two things I don’t get,

  1. Do you need to wrap every custom component with react.createElement(StyleContext.Consumer)?
  2. How do I include the same context reference in each component’s script? Imagine the above code in separate two separate modules, how do I get that same context / pass a reference down to each component module? Do I even need to?

I just now looked through react.dev/learn/passing-data-deeply-with-context, and I’m still not really getting it, especially when the docs use XML syntax and lua absolutely does not have that.

If anyone could help explain this, I’d appreciate it.
Thanks.

2 Likes