HooksForUI
Usetoggle

UseToggle

This useToggle Hook is used for updating states using React's useReducer Hook.

Hook

useToggle.tsx
import { useReducer } from "react"
 
export const useToggle = () => {
    const [ state, dispatch ] = useReducer((state, action) => {
        switch(action){
            case "on" :
                return "on";
            default : 
                return "off";
        }
    }, "off");
    return { state, dispatch }
}

Usage

navBar.tsx
import useToggle from 'hooks/useToggle';
 
const { state, dispatch } = useToggle();
 
return (
    <div>
        <button
            onClick={() => {
                dispatch("off")
            }}
        >
            Toggle
        </button>
        
        {state === "on" && <Modal dispatch={dispatch} /> }
    </div>
)