JAVASCRIPT
Build a Reusable useToggle Custom Hook
Create a versatile useToggle custom hook in React to easily manage boolean state (e.g., for modals, dark mode) across multiple components, enhancing reusability.
import React, { useState, useCallback } from 'react';
// Custom Hook: useToggle
const useToggle = (initialValue = false) => {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => {
setValue(currentValue => !currentValue);
}, []); // No dependencies needed for simple toggle
return [value, toggle];
};
// Component using the custom hook
function ToggleExample() {
const [isDarkMode, toggleDarkMode] = useToggle(false);
const [isModalOpen, toggleModal] = useToggle(false);
return (
<div>
<h2>useToggle Custom Hook Example</h2>
<div>
<p>Dark Mode is: {isDarkMode ? 'On' : 'Off'}</p>
<button onClick={toggleDarkMode}>Toggle Dark Mode</button>
</div>
<div style={{ marginTop: '20px' }}>
<p>Modal is: {isModalOpen ? 'Open' : 'Closed'}</p>
<button onClick={toggleModal}>Toggle Modal</button>
{isModalOpen && (
<div style={{
border: '1px solid black',
padding: '20px',
marginTop: '10px',
backgroundColor: 'lightgray'
}}>
<h3>This is a Modal!</h3>
<p>Content goes here.</p>
<button onClick={toggleModal}>Close Modal</button>
</div>
)}
</div>
</div>
);
}
export default ToggleExample;
How it works: This snippet demonstrates a `useToggle` custom hook that abstracts the logic for managing a simple boolean state. It takes an optional initial value and returns the current boolean state and a `toggle` function. The `toggle` function uses `useCallback` to ensure its identity is stable across renders, which is good practice for custom hooks. This hook can be reused across different components to manage various on/off states like dark mode, modal visibility, or menu toggles.