custom hooks

useToggle( )

The code provided in this article is simplified as much as possible to avoid overwhelming the reader with code and to convey the essence of the problem and its solution. In interactive examples, heading tags (`h1...h6`) are replaced with span tags to prevent potential conflicts with the main page structure.

Explanation

Toggling state between true and false is a common requirement in React applications. Whether it's showing or hiding modals, toggling UI component visibility, or responding to user interactions, useToggle can make handling these scenarios much simpler.

It simplifies the process of toggling boolean values in React components. The hook accepts an initial boolean value and provides a current state and a function to effortlessly toggle it between true and false.

By encapsulating this toggle logic into a reusable hook, we can write cleaner and more concise code, enhancing the readability and maintainability of our React applications. Feel free to experiment with the useToggle hook in your projects to improve user experience and simplify state management.

Usage Cases

  • Toggle Element Visibility: Control the visibility of elements like modals, dropdowns, sidebars, menus, navigation, or tooltips.
  • Manage Long Text Blocks: Implement "Read More/Read Less" functionality for long blocks of text.
  • Manage Component State: Control the state of sidebars, menus, or accordions.
  • Toggle Component Views: Switch between different views or modes within a component.

Creation

Code implementation
1const useToggle = (initialState: boolean = false): [boolean, () => void] => {
2 const [state, setState] = useState(initialState);
3
4 // Define and memoize the toggle function using the `useCallback` hook,
5 // ensuring consistent behavior if we pass down the component.
6 // This function switches the boolean value to its opposite
7 const toggle = useCallback(() => {
8 setState((state) => !state);
9 }, []);
10
11 return [state, toggle];
12};
13
14export default useToggle;
15

Reference

Code implementation
1const [state, toggle] = useToggle(initialState?)
2

Parameters

NameTypeDescription
initialState (optional)booleanThe boolean value you want the state to be initially. Defaults to `false`.

Return Values

NameTypeDescription
statebooleanThe boolean value representing the current state.
toggle() => void A function that toggles the `state` to its opposite based on the current value.

Example Usages

Managing Long Text Visibility

This example showcases the implementation of a custom hook, useToggle, enabling users to expand or collapse text content dynamically. By allowing users to toggle between a short and long text version with the "Read More / Read Less" functionality, it significantly enhances readability and user experience.

Code implementation
1const longText = loadData(3).join(' ');
2
3// Slice the long text string to create a shorter version
4const shortTextVersion = `${longText.slice(0, 50)}...`;
5
6const Container: FC = () => {
7 // Destructuring the state and the toggle function from the `useToggle` hook
8 const [isExpanded, handleToggleExpansion] = useToggle();
9
10 return (
11 <Layer title="Container">
12 {/* Displaying either the full text or the short text based on the `isExpanded` state */}
13 <Text>{isExpanded ? longText : shortTextVersion}</Text>
14 <div className="flex w-full justify-center">
15 {/* Rendering a Button component with dynamic text based on the `isExpanded` state */}
16 <Button onClick={handleToggleExpansion}>
17 {isExpanded ? 'Read Less' : 'Read More'}
18 </Button>
19 </div>
20 </Layer>
21 );
22};
23
An interactive output of the code above

Managing Menu Visibility

This example demonstrates how to manage menu visibility using a custom hook useToggle. By using the hook, the component toggles the isOpen state, which determines whether the menu is displayed or hidden. The menu is conditionally rendered based on the isOpen state, providing an interactive user interface. This approach allows for more reusable and cleaner state management for handling common toggle actions, such as opening and closing menus.

Code implementation
1const menuItems = loadData(3);
2
3const Container: FC = () => {
4 // Destructuring the state and toggle function from the custom hook
5 // to manage menu visibility state
6 const [isOpen, handleToggleMenu] = useToggle();
7
8 return (
9 <Layer title="Container">
10 <div className="flex w-full justify-center">
11 <Button onClick={handleToggleMenu}>
12 {isOpen ? 'Close Menu' : 'Open Menu'}
13 </Button>
14 </div>
15 {/* Conditional rendering based on the `isOpen` state */}
16 {isOpen && (
17 <List
18 items={menuItems}
19 onClick={() => {}}
20 />
21 )}
22 </Layer>
23 );
24};
25
An interactive output of the code above

Toggling Between Term Title and Description

This example illustrates the use of a custom hook, useToggle, to manage the visibility state of a term card component. By toggling between displaying the term title and its description, users can interactively explore information, enhancing user experience and understanding within the application interface.

Code implementation
1const term = {
2 title: '"Closure"',
3 discription: `A closure is the combination of a function bundled together
4 (enclosed) with references to its surrounding state (the lexical environment).`,
5};
6
7const Container: FC = () => {
8 // Destructuring the state and toggle function from the custom hook
9 // to manage visibility state
10 const [isTitleView, handleToggleCard] = useToggle(true);
11
12 return (
13 <Layer title="Container">
14 <div className="flex w-full justify-center">
15 <Button onClick={handleToggleCard}>
16 Show {isTitleView ? 'description' : 'term title'}
17 </Button>
18 </div>
19 <Text className="h-48">
20 {/* Conditional rendering of content based on the `isTitleView` state */}
21 {isTitleView ? term.title : term.discription}
22 </Text>
23 </Layer>
24 );
25};
26
An interactive output of the code above
Last updated on by @skrykateSuggest an improvement on Github repository.