Lesson 4 of 6
UI frameworks, part 1: React-lua, elements, props and state
Part 1 of 2 on Roblox UI frameworks, installing React-lua with Wally and learning elements, components, props and state by rebuilding pieces of Beacon Yard's shop.
By the end you can
- Explain the difference between changing UI by hand and describing UI as a function of state
- Install React-lua with Wally and map its packages into the game with Rojo
- Write a component with createElement, pass it props and give it state with useState
Before this: UI fundamentals: ScreenGui, UDim2, layouts, ModuleScripts and require
1Count the property writes
This lesson and the next are one 100-minute topic split in two. Part 1 teaches the ideas and installs the library. Part 2 rebuilds the whole shop.
Open src/client/ShopGui.luau and find the Coin Pack button. Building that one button takes twelve property writes, a corner, and a click handler. Opening the shop is one more write, panel.Visible = true, in a handler at the bottom of the file. Closing it is another, in a different handler. Every change to the screen is a line someone had to remember.
local packReady = Ids.COIN_PACK_PRODUCT_ID > 0
local pack = Instance.new("TextButton")
pack.Name = "CoinPack"
pack.Size = UDim2.new(1, 0, 0, 84)
pack.BackgroundColor3 = if packReady then Color3.fromRGB(168, 112, 28) else Color3.fromRGB(48, 52, 60)
pack.BorderSizePixel = 0
pack.AutoButtonColor = true
pack.FontFace = boldFont()
pack.TextSize = 26
pack.TextColor3 = Color3.fromRGB(255, 255, 255)
pack.TextWrapped = true
pack.Text = if packReady
then string.format("Coin Pack\n%d coins", prices.COIN_PACK_COINS)
else "Coin Pack\nset COIN_PACK_PRODUCT_ID"
pack.LayoutOrder = 4
pack.Parent = panel
corner(pack, 10)
The HUD works the same way. When the round changes phase, a handler rewrites the label text.
The HUD through one drill. Each change is a handler writing a property.
Transcript
- 0:00 The HUD starts in Idle, with coins and a timer.
- 0:03 Active replaces the phase name while the drill runs.
- 0:10 Cooldown is the short pause before Idle returns.
- 0:18 The shop opens above the HUD. Close hides it locally.
In ShopGui as it is, what happens to the Coin Pack label if Ids.COIN_PACK_PRODUCT_ID changes while the game runs?
Answer
Nothing; the label was written once at start and no code writes it again. pack.Text is set once, inside ShopGui.start. Hand-built UI only changes when some line of code changes it, so every new piece of state means new handler code.
Open this step in lesson mode · Link to this step · This confused me
2UI as a function of state
A UI framework flips the job around. Instead of writing "change this label now", you write one function that says what the screen should look like for a given UI stateUI stateThe data a screen shows right now, such as whether the shop is open or which item is waiting for the server.Think of it as the facts the screen is a picture of., and the framework makes the real Instances match. Change the state and it works out which properties to update. That function is a ComponentComponentA function that takes inputs (props and state) and returns a description of some UI.Think of it as a stamp: same inputs, same picture..
-- Not React yet: the idea in plain Luau.
-- A component is a function from state to a description.
local function shop(state)
return {
visible = state.open,
packText = if state.packReady
then "Coin Pack\n" .. state.packCoins .. " coins"
else "Coin Pack\nset COIN_PACK_PRODUCT_ID",
}
end
local closed = shop({ open = false, packReady = false, packCoins = 50 })
local open = shop({ open = true, packReady = true, packCoins = 50 })
print(tostring(closed.visible) .. " " .. tostring(open.visible))
print(open.packText)
false true
Coin Pack
50 coinsIn the cell above, what would a real framework do with the two descriptions?
Answer
Compare them and write only the properties that differ to the real Instances. This is reconciliation: the framework keeps the last description, compares it with the new one, and updates only what changed, here Visible and the pack label.
Open this step in lesson mode · Link to this step · This confused me
3React-lua
React is the most used UI library on the web. React-lua is a translation of React 17 into Luau. It is available on Wally in two compatible packages: the community distribution jsdotlua/react (17.2.1), which Beacon Yard pins at m09-react-shop1, and Roblox's own read-only mirror Roblox/react-luau, published on Wally as roblox/react and roblox/react-roblox under the MIT licence23. Roact, the older library many tutorials still show, was archived in December 20234.
Because React-lua follows React 17 closely, most React advice from the web applies, and the skills transfer directly to web work too.
Other ways pros do this
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| roblox/react (Roblox/react-luau) | Roblox's official React-lua mirror, published as roblox/react and roblox/react-roblox on Wally. | New projects that want the latest upstream Roblox releases. | A read-only mirror: you cannot open pull requests, and docs lean on the React website. |
| jsdotlua/react (jsdotlua/react-lua) | The community React-lua distribution on Wally (17.2.1), pinned in Beacon Yard's wally.toml. | Existing projects and repos that already pin jsdotlua/react and jsdotlua/react-roblox. | Older release (17.2.1) behind Roblox's upstream mirror, though the component and hook API is the same. |
| Roact | Roblox's earlier React-like library. | Only when maintaining old code. | Archived in December 2023. Do not start new work with it. |
| @rbxts/react with roblox-ts | The same React-lua runtime, written in TypeScript with JSX. | Teams that write TypeScript and want JSX. | A whole extra toolchain; covered in the ecosystem tools lesson. |
You want React-lua in a Roblox project managed with Wally. Which approach is right?
Answer
Add React and ReactRoblox through Wally (roblox/react for new projects, or jsdotlua/react as pinned in Beacon Yard). Wally installs the Luau React and ReactRoblox packages (Beacon Yard pins jsdotlua/react@17.2.1; new projects can also pick Roblox's official roblox/react mirror). Roact is archived, and npm's react is JavaScript.
Open this step in lesson mode · Link to this step · This confused me
4Install it with Wally and Rojo
WallyWallyA package manager for Roblox: wally.toml lists libraries, wally install downloads them into Packages.Think of it as npm or pip for Luau libraries. is a package manager: you list libraries in wally.toml, and wally install downloads them. Beacon Yard pins Wally 0.3.2 in rokit.toml, and the toolchain lesson covers it in depth. React-lua is two packages: React, the core, and ReactRoblox, the part that turns elements into Roblox Instances (the equivalent of ReactDOM on the web). You add them to wally.toml, run wally install, and map the Packages folder it creates into ReplicatedStorage so both client and server code can require it.
[dependencies]
React = "jsdotlua/react@17.2.1"
ReactRoblox = "jsdotlua/react-roblox@17.2.1"
"ReplicatedStorage": {
"Packages": { "$path": "Packages" },
"Shared": { "$path": "src/shared" }
}
Beacon Yard pins jsdotlua/react@17.2.1 and jsdotlua/react-roblox@17.2.1 at m09-react-shop; on a brand-new project you can also pin Roblox's official roblox/react and roblox/react-roblox packages3. Whichever you choose, pin an exact version, commit wally.lock, and keep Packages/ out of Git, since anyone can rebuild it with wally install.
Go deeper What wally.lock is for
wally install writes wally.lock, a record of the exact version of every package in the dependency tree, including the ones your packages depend on. Commit it. Everyone who runs wally install then gets the same versions, and a CI job can rebuild Packages/ from it.
Put the install steps in order.
Answer
1. Add React and ReactRoblox under [dependencies] in wally.toml 2. Run wally install in the repo folder 3. Map Packages into ReplicatedStorage in default.project.json 4. Restart rojo serve and check Packages appears in Explorer 5. require ReplicatedStorage.Packages.React from a LocalScript. Declare, download, map, sync, use. Skipping the mapping is the most common mistake: wally install fills a folder on disk that Rojo never sends to Studio.
Open this step in lesson mode · Link to this step · This confused me
5Elements and components
An element is a small table that describes one Instance: its class, its properties and its children. You make one with React.createElement, usually shortened to e. A component is a function that takes props and returns elements.
local React = require(ReplicatedStorage.Packages.React)
local e = React.createElement
local function BuyButton(props)
return e("TextButton", {
Size = UDim2.new(1, 0, 0, 84),
BackgroundColor3 = props.color,
Text = string.format("%s\n%d coins", props.name, props.price),
LayoutOrder = props.order,
[React.Event.Activated] = props.onBuy,
}, {
Corner = e("UICorner", { CornerRadius = UDim.new(0, 10) }),
})
end
[React.Event.Activated] connects the button's Activated event. The keys of the children table become the children's Name, so this button gets a child called Corner5. ShopGui already has a buyButton helper for Speed and Shield. The difference is what happens later: the helper builds a button once, while a component is run again whenever its props or state change.
What text does this element show?
e(BuyButton, { name = "Shield", price = 40, order = 3,
color = Color3.fromRGB(36, 92, 168), onBuy = buy })
Answer
Shield, then 40 coins on the next line. The component formats "%s\n%d coins" with the props, so the label reads Shield, a line break, and 40 coins. Props flow in from the parent; the component never fetches them itself.
Open this step in lesson mode · Link to this step · This confused me
6State and the doorbell
Props come from the parent. State belongs to the component and changes over time. React.useState(false) returns the current value and a function that sets a new one. Calling the setter tells React to run the component again and update the Instances.
local function Shop(props)
local open, setOpen = React.useState(false)
React.useEffect(function()
local connection = props.shopOpen.OnClientEvent:Connect(function()
setOpen(true)
end)
return function()
connection:Disconnect()
end
end, {})
return e("Frame", { Visible = open, Size = UDim2.fromOffset(400, 480) })
end
Both are hooks. The rule of hooks: call them at the top level of a component, never inside an if, a loop or a callback.
ShopOpen.OnClientEvent is a doorbell. When the server rings it, the handler opens the shop by setting state. useEffect is where a component hangs its doorbell wires: it runs after the component appears, and the function it returns runs when the component goes away.
Think of it as A doorbell
Both sidesRemember: An event and :Connect is a doorbell.
While the shop is closed, ShopOpen fires and the handler calls setOpen(true). What happens next?
Answer
React runs Shop again with open = true and sets the Frame's Visible to true. The setter stores the new value and schedules a render. The new description says Visible = true, and React writes just that property.
Open this step in lesson mode · Link to this step · This confused me
7Where the doorbell breaks
Where does it break?“A doorbell” is a good picture of an event and :connect. Where does it stop being true?
It breaks here. One visit can ring many times (Touched fires per body part), handlers have no promised order, and a chime you never unwire keeps ringing: connections leak until you disconnect them.
The true model. An RBXScriptSignal calls every connected handler each time it fires, possibly deferred to the next resumption point. Handlers must tolerate repeats and must be disconnected when their owner goes away.
A doorbell you never disconnect keeps ringing after you moved out. If the effect above did not return the cleanup function, each time the shop component was removed and added again, a new connection would pile up, and an old one would try to set state on a component that no longer exists. Effects also give no promise about order between components, so never let one effect depend on another having run first.
This effect has a leak. Which line is wrong?
React.useEffect(function()
props.shopOpen.OnClientEvent:Connect(function()
setOpen(true)
end)
end, {})
Answer
Line 2: props.shopOpen.OnClientEvent:Connect(function(). Fixed: local connection = props.shopOpen.OnClientEvent:Connect(...) and return function() connection:Disconnect() end. The connection returned by Connect is dropped, so nothing can disconnect it. Keep it and return a cleanup function that calls Disconnect.
Open this step in lesson mode · Link to this step · This confused me
8Build along: install React-lua and mount a portal
Build along
wally.tomldefault.project.jsonsrc/client/ShopGui.luausrc/client/ShopApp.luau
Check out
m09-react-shop, inspectwally.toml(React = "jsdotlua/react@17.2.1"andReactRoblox = "jsdotlua/react-roblox@17.2.1"), and runwally installin the repo folder.You should see wally.lock matches wally.toml and a Packages folder holds React and ReactRoblox.
Inspect the
Packagesmapping underReplicatedStorageindefault.project.json, startrojo serve, and connect Studio.You should see ReplicatedStorage.Packages shows up in Studio's Explorer after Rojo syncs.
Open
src/client/ShopGui.luauandsrc/client/ShopApp.luauto see howShopGui.start()builds theBeaconShopScreenGuiwithUiScaleand portalsShopAppinto it, then press Play and open the shop.You should see During Play, holding the quartermaster prompt opens BeaconShop mounted by ShopGui.luau through ReactRoblox.createRoot and createPortal.
Open this step in lesson mode · Link to this step · This confused me
9Challenges
Level 1, Apprentice
Challenge
Write a CoinCounter component that shows a coin count passed in as a prop.
- Start from
- The game at milestone m09 (download)
Done means
- A CoinCounter component takes coins as a prop and shows Coins: 0
- It is rendered through ReactRoblox.createRoot and createPortal into PlayerGui
- Changing the prop in code changes the label on the next Play
Hints
- Follow ShopGui.luau's createRoot + createPortal pattern in a small scratch module.
- string.format("Coins: %d", props.coins)
- The parent passes the prop; the component does not read leaderstats itself.
Level 2, Builder
Challenge
Make the counter live: keep the coin count in state and update it from the leaderstats Coins value.
- Start from
- The game at milestone m09 (download)
Done means
- CoinCounter follows the real leaderstats Coins value
- The connection is made in useEffect and disconnected in its cleanup
- Picking up a coin updates the label without any manual property write
Hints
- Hold the count in useState.
- See how ShopApp.luau subscribes to leaderstats.Coins inside useEffect.
- Return a function from the effect that disconnects.
Why does the shop's effect pass an empty table {} as the second argument to useEffect?
Answer
So it runs once when the component appears and cleans up when it goes away. An empty dependency list means nothing can make the effect run again, so it connects once on mount and disconnects on unmount.
Open this step in lesson mode · Link to this step · This confused me
10Recap
Retiring the analogy
You no longer need “a doorbell”. An RBXScriptSignal calls every connected handler each time it fires, possibly deferred to the next resumption point. Handlers must tolerate repeats and must be disconnected when their owner goes away.
Recap
- Hand-built UI changes only where you write a property; a framework renders UI from state and updates only what differs.
- React-lua is a Luau port of React 17; install React and ReactRoblox with Wally (jsdotlua/react in Beacon Yard, or roblox/react in new projects) and map Packages with Rojo.
- Components take props, keep state with useState, and wire events in useEffect with a cleanup that disconnects.
An event and :Connect is a doorbell, until one visit can ring many times (Touched fires per body part), handlers have no promised order, and a chime you never unwire keeps ringing: connections leak until you disconnect them.
Queued for review
Next UI frameworks, part 2: the React-lua shop, Fusion, Vide and when to use one
Open this step in lesson mode · Link to this step · This confused me