Created
September 4, 2024 13:29
-
-
Save cxmeel/42c298bcbce74a4e1e2e38c035ab8d50 to your computer and use it in GitHub Desktop.
useSelector hook for BasicState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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