Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Created September 4, 2024 13:29
Show Gist options
  • Save cxmeel/42c298bcbce74a4e1e2e38c035ab8d50 to your computer and use it in GitHub Desktop.
Save cxmeel/42c298bcbce74a4e1e2e38c035ab8d50 to your computer and use it in GitHub Desktop.
useSelector hook for BasicState
local React = require("@pkgs/React")
local useMemo = React.useMemo
local useRef = React.useRef
type Predicate<T = unknown> = (a: T?, b: T) -> boolean
local function isStrictEqual(a: unknown?, b: unknown)
return a == b
end
local function useLatest<T>(value: T, predicate: Predicate<T>?): { current: T }
local ref = useRef(value)
useMemo(function()
local predicateFn: Predicate<T> = predicate or isStrictEqual
if not predicateFn(ref.current, value) then
ref.current = value
end
end, { value })
return ref :: { current: T }
end
return useLatest
local React = require("@pkgs/React")
local useLatest = require("./useLatest")
local useEffect = React.useEffect
local useState = React.useState
type BasicStateStore = { [any]: any }
local function useSelector<T>(
store: BasicStateStore,
selector: (state: BasicStateStore) -> T
): T
local value, setValue = useState(selector(store:GetState()))
local selectorRef = useLatest(selector)
useEffect(function()
local connection = store.Changed:Connect(function()
local state = store:GetState()
setValue(selectorRef.current(state))
end)
return function()
connection:Disconnect()
end
end, { selector })
return value
end
return useSelector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment