Created
April 8, 2022 23:49
-
-
Save Noitidart/1281013f67f280788f1cc17e2df51849 to your computer and use it in GitHub Desktop.
maybe useful maybe not. i made but never used it.
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
import { useMemo, useRef } from 'react'; | |
import { useMemoizedFn } from 'ahooks'; | |
import { noop } from 'lodash'; | |
type UseRadioInputs = { | |
// Defaults to undefined | |
defaultValue?: any; | |
onChange?: (value: any) => void; | |
}; | |
function useRadio(inputs: UseRadioInputs) { | |
const latestValue = useRef(inputs.defaultValue); | |
const stableOnChange = useMemoizedFn(inputs.onChange || noop); | |
const api = useMemo( | |
() => ({ | |
setValue: (nextValue: any) => { | |
if (api.getValue() !== nextValue) { | |
latestValue.current = nextValue; | |
stableOnChange?.(latestValue.current); | |
} | |
}, | |
getValue: () => latestValue.current | |
}), | |
[latestValue, stableOnChange] | |
); | |
return api; | |
} | |
export default useRadio; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment