This content originally appeared on DEV Community and was authored by Mahesh Galange
Table of Contents
- What Are Custom Hooks?
- Why Use Custom Hooks?
- How to Create One β Example
- Best Practices & Common Mistakes
What Are Custom Hooks?
Custom Hooks are JavaScript functions that start with the word use and allow you to extract component logic into reusable functions. They use Reactβs built-in hooks (like useState, useEffect) under the hood and follow the same rules.
Why Use Custom Hooks?
Hereβs what you gain:
Reusability: Share logic across multiple components
Cleaner Code: Keep your components focused on UI
Composability: Combine multiple hooks into one
How to Create One β Example
Letβs create a custom hook called useLocalStorage.
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Usage:
function ThemeToggle() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Switch to {theme === 'light' ? 'dark' : 'light'} mode
</button>
);
}
Final Thoughts
Thatβs a wrap on custom hooks! Theyβre powerful, reusable, and help keep your code clean and modular. I hope this guide helps you create your own and apply them confidently in your React projects.
This was my first blogβif you liked it or found it helpful, feel free to connect or share your feedback!
This content originally appeared on DEV Community and was authored by Mahesh Galange