mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
24 lines
508 B
TypeScript
24 lines
508 B
TypeScript
import {useState, useCallback} from 'react';
|
|
|
|
export type UseToggle = (state: boolean) => [
|
|
boolean, // state
|
|
(nextValue?: boolean) => void // toggle
|
|
];
|
|
|
|
const useToggle: UseToggle = state => {
|
|
const [value, setValue] = useState<boolean>(state);
|
|
|
|
const toggle = useCallback((nextValue?: boolean) => {
|
|
if (typeof nextValue !== 'undefined') {
|
|
setValue(!!nextValue);
|
|
return;
|
|
}
|
|
|
|
setValue(value => !value)
|
|
}, [setValue]);
|
|
|
|
return [value, toggle];
|
|
};
|
|
|
|
export default useToggle;
|