JAVASCRIPT
Create a Reusable Toggle Hook (useToggle)
Build a custom `useToggle` React hook for easily managing boolean states, perfect for UI elements like modals, dropdowns, or dark mode switches.
import React, { useState, useCallback } from 'react';
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
// Memoize the toggle function to prevent unnecessary re-renders
const toggle = useCallback(() => {
setValue((prevValue) => !prevValue);
}, []);
return [value, toggle];
}
function ToggleComponent() {
const [isModalOpen, toggleModal] = useToggle(false);
const [isDarkMode, toggleDarkMode] = useToggle(false);
const appStyle = {
background: isDarkMode ? '#333' : '#FFF',
color: isDarkMode ? '#FFF' : '#333',
padding: '20px',
minHeight: '150px',
borderRadius: '8px',
border: '1px solid #ccc'
};
const modalStyle = {
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
background: 'white',
padding: '30px',
border: '1px solid #ccc',
boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
zIndex: 1000,
display: isModalOpen ? 'block' : 'none'
};
return (
<div style={appStyle}>
<h2>Custom Toggle Hook Example</h2>
<button onClick={toggleModal}>
{isModalOpen ? 'Close Modal' : 'Open Modal'}
</button>
<button onClick={toggleDarkMode} style={{ marginLeft: '10px' }}>
{isDarkMode ? 'Light Mode' : 'Dark Mode'}
</button>
{isModalOpen && (
<div style={modalStyle}>
<h3>Modal Content</h3>
<p>This is a modal controlled by useToggle.</p>
<button onClick={toggleModal}>Close</button>
</div>
)}
<p>Dark mode is {isDarkMode ? 'ON' : 'OFF'}</p>
<p>Modal is {isModalOpen ? 'open' : 'closed'}</p>
</div>
);
}
export default ToggleComponent;
How it works: Custom hooks allow you to extract component logic into reusable functions. The `useToggle` hook demonstrates this by encapsulating the common pattern of managing a boolean state. It takes an optional `initialValue` and returns the current boolean state and a `toggle` function. The `useCallback` is used to memoize the `toggle` function, ensuring it doesn't change on every render, which can be beneficial for performance when passed down to child components. This hook simplifies component code by abstracting away the boilerplate for boolean state management.