@shopify/polaris
Version:
Shopify’s product component library
20 lines (19 loc) • 899 B
JavaScript
import { useState, useCallback } from 'react';
export function useToggle(initialState) {
const [state, setState] = useState(initialState);
const toggle = useCallback(() => setState((state) => !state), []);
// cast needed to say this returns a two item array with the items in
// their specific positions instead of `(typeof state | typeof toggle)[]`
return [state, toggle];
}
export function useForcibleToggle(initialState) {
const [state, setState] = useState(initialState);
const toggles = {
toggle: useCallback(() => setState((state) => !state), []),
forceTrue: useCallback(() => setState(true), []),
forceFalse: useCallback(() => setState(false), []),
};
// cast needed to say this returns a two item array with the items in
// their specific positions instead of `(typeof state | typeof toggles)[]`
return [state, toggles];
}