Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Custom Hooks let you extract component logic into reusable functions. They're JavaScript functions that start with "use" and can call other Hooks.
1. Identify repeated logic:
2. Extract into custom Hook:
3. Use it in components:
Toggle visibility, dark mode, and more
// Custom Hook
function useToggle(initialValue = false) {
const [value, setValue] = React.useState(initialValue);
const toggle = () => setValue(v => !v);
const setTrue = () => setValue(true);
const setFalse = () => setValue(false);
return [value, { toggle, setTrue, setFalse }];
}
// Using the Hook
function App() {
const [isVisible, visibilityControls] = useToggle(true);
const [isDarkMode, darkModeControls] = useToggle(false);
const [isExpanded, expandControls] = useToggle(false);
React.useEffect(() => {
const body = document.body;
if (isDarkMode) {
body.classList.add('dark-mode');
} else {
body.classList.remove('dark-mode');
}
return () => body.classList.remove('dark-mode');
}, [isDarkMode]);
return (
<div className={`container ${isDarkMode ? 'dark-mode' : ''}`}>
<h1>🎛️ useToggle Hook</h1>
<div className="section">
<h3>Visibility Toggle</h3>
<button onClick={visibilityControls.toggle} className="btn-primary">
{isVisible ? 'Hide' : 'Show'} Content
</button>
{isVisible && (
<div className="content">
✨ This content can be toggled!
</div>
)}
</div>
<div className="section">
<h3>Dark Mode Toggle</h3>
<button onClick={darkModeControls.toggle} className="btn-primary">
{isDarkMode ? '☀️ Light' : '🌙 Dark'} Mode
</button>
</div>
<div className="section">
<h3>Expandable Section</h3>
<button onClick={expandControls.toggle} className="btn-primary">
{isExpanded ? 'Collapse' : 'Expand'}
</button>
{isExpanded && (
<div className="content">
<p>Here's some extra content!</p>
<p>Custom Hooks make this so easy.</p>
</div>
)}
</div>
<div className="info">
💡 One Hook, multiple uses!
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);Loading preview...
Always name custom Hooks starting with "use" so React knows it's a Hook.
Use clear names: useWindowSize, useLocalStorage, useForm
Each custom Hook should have a single, clear purpose. Don't make "god Hooks" that do everything.
Return arrays for simple values, objects for many values. Make it easy to use!
Custom Hooks extract and share stateful logic between components without repeating code.
Each call to a custom Hook gets its own state. Hooks share logic, not state!
Follow the naming convention so React and linters can verify Hook rules.
Custom Hooks must follow all the same rules as built-in Hooks (top level, React functions only).