Rules
- naming convention: ‘use’ prefix
- Called at the top level
- never be nested in loops, conditions, nested function
- → ensure React maintain same order of hooks on every render
Best Practices
- keep custom hooks focused on one task
Benefits
- Reduces duplication
- Abstraction, Separation of concern → easier to read
Custom Hooks in React: The Ultimate UI Abstraction Layer
뭔가 데이터 fetch하고 loading이 걸릴 때 쓰기 좋은 것 같은데
- Call
import useCategories from './useCategories' function Categories() { const { categories, loading } => useCategories(); if (loading) { return < Loading />; } return ( <div> { categories.map((category) => ( < CategoryCard key={category.id} category={category.name} /> ))} </div> ); }
- Define
import { useEffect, useState } from 'react'; function useCategories() { const [categories, setCategories] = useState([]); const [loading, setLoading] = useState(true); const url = "https://example.org/products.json"; useEffect(() => { async function fetchData() { try { const response = await fetch(url); if (!response.ok) { throw new Error(`Response status: ${response.status}`); } const json = await response.json(); } catch(error) { console.error(error.message); } finally { setLoading(false); } } fetchData(); }, []); return { categories, loading }; }