Reusable Hook for Managing Open/Close State in React Modals
DevQuery Adminasked 5mo ago
3 Upvotes
0 Downvotes
1 Answers
2 Views
3
How can I create a reusable React hook for managing the open and close states of modals? Can you provide an example of such a hook and explain its usage?
1 Answer(s)
DevQuery Adminanswered 5mo ago
0 Upvotes
0 Downvotes
0
Instead of using separate state variables for each modal, you can use a reusable custom hook to manage the open/close state. Here's how you can implement it in TypeScript:
import { useCallback, useState } from 'react';
type UseSwitchReturnType = [boolean, () => void, () => void];
/**
* A custom hook to manage the open/close state.
*
* @param defaultState - The initial state of the switch.
* @returns A tuple containing the current state, a function to set the state to true (on), and a function to set the state to false (off).
*/
export const useSwitch = (defaultState: boolean): UseSwitchReturnType => {
const [state, setState] = useState<boolean>(defaultState);
const on = useCallback((): void => setState(true), []);
const off = useCallback((): void => setState(false), []);
return [state, on, off];
};
Explanation:
useSwitch
Hook: This custom hook manages a boolean state, which is useful for toggling between two states, like open/close for modals.- Parameters:
defaultState
: The initial state of the switch (e.g.,true
for open,false
for closed).
- Returns:
- The current state (
boolean
). on
: A function to set the state totrue
.off
: A function to set the state tofalse
.
- The current state (
This approach is effective for managing the state of multiple modals or toggleable components without needing separate state variables for each one.