Overview:
I've created a custom useToggle
react hook and I want to use two instances in one component. A toggle for the "Privacy Policy" and a toggle for the "Terms and Conditions."
Question
How can I use the same useToggle
hook to get different constants for each useToggle hook such as the following below. A solution for [isToggled, toggle]
or { isToggled, toggle }
works. Object destructuring is preferred if it is possible.
const privacyPolicy = [isToggled, toggle] = useToggle();const terms = [isToggled, toggle] = useToggle();<button title="Privacy Policy" onClick={privacyPolicy.toggle} /><button title="Terms & Conditions" onClick={terms.toggle} />
useToggle.ts
// Imports: Dependenciesimport { useCallback, useState } from 'react';// Imports: TypeScript Typesimport { TReactHookUseToggle } from '@jefelewis/unison-types';// React Hook: Use Toggleexport const useToggle = (initialState: boolean = false): TReactHookUseToggle => { // React Hooks: State const [isToggled, setIsToggled] = useState<boolean>(initialState); // Toggle const toggle: () => void = useCallback((): void => setIsToggled((prevState: boolean) => !prevState), []); return [isToggled, toggle];};