Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Created April 8, 2022 23:49
Show Gist options
  • Save Noitidart/1281013f67f280788f1cc17e2df51849 to your computer and use it in GitHub Desktop.
Save Noitidart/1281013f67f280788f1cc17e2df51849 to your computer and use it in GitHub Desktop.
maybe useful maybe not. i made but never used it.
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