Cum să creezi custom hooks în React
In this tutorial, you'll learn about Cum să creezi custom hooks în React. We cover key concepts, practical examples, and best practices.
Custom hooks sunt funcții care reutilizează logica cu stare între componente. Ele încep cu "use" și pot apela alte hooks.
The Problem
Aceeași logică (fetch date, formular, localStorage) se repetă în mai multe componente. Copy-paste duce la cod inconsistent și greu de întreținut.
The Wrong Way
function UserList() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/users')
.then(res => res.json())
.then(d => { setData(d); setLoading(false); });
}, []);
// aceeași logică și în ProductList, OrderList...
}
The Right Way
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(d => { setData(d); setLoading(false); });
}, [url]);
return { data, loading };
}
// Folosire
function UserList() {
const { data, loading } = useFetch('/api/users');
if (loading) return <p>Se încarcă...</p>;
return <pre>{JSON.stringify(data)}</pre>;
}
Output: Datele fetch-uite în orice component, fără duplicare.
Step-by-Step Fix
1. Identifică logica care se repetă
Găsește pattern-ul comun (fetch, form, scroll, localStorage).
2. Extrage într-o funcție care începe cu "use"
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initial;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
3. Folosește hook-ul în componente
function Settings() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>{theme}</button>;
}
Prevention Tips
- Numele hook-ului trebuie să înceapă cu "use"
- Nu apela hooks în interiorul condițiilor sau buclelor
- Fiecare instanță a unui custom hook are stare independentă
Common Mistakes
- Nume care nu începe cu "use" — React nu poate verifica regulile hooks
- Hooks apelate condițional — încalcă regulile hooks
- Custom hook prea complex — face prea multe; desparte în hooks mai mici
- Fără parametri — hook-ul nu este reutilizabil fără configurare
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tools integrate seamlessly with React for enhanced productivity and security.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro