JAVASCRIPT
Custom Hook for Toggling UI Elements (e.g., Modals, Drawers)
Create a reusable React custom hook, `useToggle`, to effortlessly manage the visibility state of modals, sidebars, or any UI component with a simple toggle.
import React, { useState, useCallback } from 'react';
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => {
setValue(currentValue => !currentValue);
}, []);
return [value, toggle];
}
function MyComponent() {
const [isModalOpen, toggleModal] = useToggle();
const [isSidebarVisible, toggleSidebar] = useToggle(true); // Start visible
return (
<div>
<button onClick={toggleModal}>
{isModalOpen ? 'Close Modal' : 'Open Modal'}
</button>
{isModalOpen && (
<div style={{ border: '1px solid black', padding: '20px', margin: '10px' }}>
<h2>Modal Content</h2>
<p>This is a modal!</p>
</div>
)}
<hr />
<button onClick={toggleSidebar}>
{isSidebarVisible ? 'Hide Sidebar' : 'Show Sidebar'}
</button>
{isSidebarVisible && (
<div style={{ border: '1px solid blue', padding: '15px', margin: '10px' }}>
<h3>Sidebar Content</h3>
<p>This is a sidebar!</p>
</div>
)}
</div>
);
}
export default MyComponent;
How it works: The `useToggle` custom hook provides a simple, reusable way to manage boolean state, perfect for toggling the visibility of UI elements like modals, dropdowns, or sidebars. It encapsulates the `useState` logic and a `useCallback` memoized toggle function, making it clean and efficient to integrate into any component that needs a simple on/off state.