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.

Project lesson, about 35 minutes, 10 steps

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

Step 1 of 10

Count 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
  1. 0:00 The HUD starts in Idle, with coins and a timer.
  2. 0:03 Active replaces the phase name while the drill runs.
  3. 0:10 Cooldown is the short pause before Idle returns.
  4. 0:18 The shop opens above the HUD. Close hides it locally.
Choose one

In ShopGui as it is, what happens to the Coin Pack label if Ids.COIN_PACK_PRODUCT_ID changes while the game runs?

In ShopGui as it is, what happens to the Coin Pack label if Ids.COIN_PACK_PRODUCT_ID changes while the game runs?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 2 of 10

UI 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..

Luau
Ctrl Enter runs the cell. Checked against the expected output
Choose one

In the cell above, what would a real framework do with the two descriptions?

In the cell above, what would a real framework do with the two descriptions?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 3 of 10

React-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

OptionWhat it isWhen pros pick itTrade-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.
RoactRoblox'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-tsThe 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.
Choose one

You want React-lua in a Roblox project managed with Wally. Which approach is right?

You want React-lua in a Roblox project managed with Wally. Which approach is right?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 4 of 10

Install 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"
json
"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 in order

Put the install steps in order.

  1. Restart rojo serve and check Packages appears in Explorer
  2. require ReplicatedStorage.Packages.React from a LocalScript
  3. Map Packages into ReplicatedStorage in default.project.json
  4. Run wally install in the repo folder
  5. Add React and ReactRoblox under [dependencies] in wally.toml

Link to this step · This confused me

Step 5 of 10

Elements 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.

luau
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.

Predict the output

What text does this element show?

e(BuyButton, { name = "Shield", price = 40, order = 3,
  color = Color3.fromRGB(36, 92, 168), onBuy = buy })
What text does this element show?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 6 of 10

State 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.

luau
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.

Choose one

While the shop is closed, ShopOpen fires and the handler calls setOpen(true). What happens next?

While the shop is closed, ShopOpen fires and the handler calls setOpen(true). What happens next?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 7 of 10

Where 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.

Find the broken line

This effect has a leak. Which line is wrong?

This effect has a leak. Which line is wrong?

Press 1 to 5 to choose, Enter to check.

Link to this step · This confused me

Step 8 of 10

Build along: install React-lua and mount a portal

  • wally.toml
  • default.project.json
  • src/client/ShopGui.luau
  • src/client/ShopApp.luau
  1. Check out m09-react-shop, inspect wally.toml (React = "jsdotlua/react@17.2.1" and ReactRoblox = "jsdotlua/react-roblox@17.2.1"), and run wally install in the repo folder.

    You should see wally.lock matches wally.toml and a Packages folder holds React and ReactRoblox.

  2. Inspect the Packages mapping under ReplicatedStorage in default.project.json, start rojo serve, and connect Studio.

    You should see ReplicatedStorage.Packages shows up in Studio's Explorer after Rojo syncs.

  3. Open src/client/ShopGui.luau and src/client/ShopApp.luau to see how ShopGui.start() builds the BeaconShop ScreenGui with UiScale and portals ShopApp into 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.

Link to this step · This confused me

Step 9 of 10

Challenges

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

Meet the criteria above, then record your own result. No test grades this check.

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

Meet the criteria above, then record your own result. No test grades this check.

Choose one

Why does the shop's effect pass an empty table {} as the second argument to useEffect?

Why does the shop's effect pass an empty table {} as the second argument to useEffect?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 10 of 10

Recap

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

  1. Hand-built UI changes only where you write a property; a framework renders UI from state and updates only what differs.
  2. 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.
  3. 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.

Next UI frameworks, part 2: the React-lua shop, Fusion, Vide and when to use one

Link to this step · This confused me