Toggle hack
import { useState } from "react";
interface UseToggleHandlers {
on: () => void;
off: () => void;
toggle: () => void;
reset: () => void;
}
type UseToggle = [boolean, UseToggleHandlers];
export const useToggle = (initialState = false): UseToggle => {
const [state, setState] = useState(initialState);
const handlers: UseToggleHandlers = {
on: () => {
setState(true);
},
off: () => {
setState(false);
},
toggle: () => {
setState((s) => !s);
},
reset: () => {
setState(initialState);
},
};
return [state, handlers];
};
Why use it?
To make the programming more functional, it has removed the context of useState, and introduced a component’s attributive state hook!
useState replaced by useToggle
setState replaced by toggle.on() or toggle.off()
const [modalVisible, setModalVisible] = useState()
----- replaced by
const [modalVisible,handleModal] = useModalVisible()
setModalVisible(true)
----- replaced by
handleModal.show()
setModalVisible(false)
----- replaced by
handleModal.hide()