ant-design/components/_util/ref.ts
jesse 09bb61e738
perf: Radio Group usePrevious instead of useState (#25122)
* perf: Radio Group usePrevious instead of useState

* fix: only re-run if value changes

* perf: put usePrevious custom Hook in _util/ref.ts

* Generics instead of any

* update
2020-06-30 10:45:16 +08:00

28 lines
605 B
TypeScript

import * as React from 'react';
export function fillRef<T>(ref: React.Ref<T>, node: T) {
if (typeof ref === 'function') {
ref(node);
} else if (typeof ref === 'object' && ref && 'current' in ref) {
(ref as any).current = node;
}
}
export function composeRef<T>(...refs: React.Ref<T>[]): React.Ref<T> {
return (node: T) => {
refs.forEach(ref => {
fillRef(ref, node);
});
};
}
export function usePrevious<T = undefined>(value: T): T | undefined {
const ref = React.useRef<T>();
React.useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}