This repository has been archived by the owner on Jan 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
useReactiveState.lua
41 lines (35 loc) · 1.52 KB
/
useReactiveState.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
local copy = require(script.Parent.Parent.copy)
local useLatest = require(script.Parent.useLatest)
--[=[
Creates a mutable state object that causes a re-render whenever a new value is assigned to a key.
@function useReactiveState
@within Hooks
@param initialState T
@return HookCreator<T>
]=]
local function useReactiveState(initialState)
return function(hooks)
if type(initialState) ~= "table" then
error("Initial state is not a table!", 2)
end
local state, update = hooks.useState(initialState)
local latestState = useLatest(state)(hooks)
local reactiveState = hooks.useMemo(function()
return setmetatable({}, {
__index = function(_, key)
return latestState.value[key]
end,
__newindex = function(_, key, value)
local newState = copy(latestState.value)
newState[key] = value
update(newState)
end,
__tostring = function()
return 'ReactiveState'
end,
})
end, {})
return reactiveState
end
end
return useReactiveState