How to Use Custom Hooks in React
Custom hooks in React allow you to extract and reuse stateful logic between components without changing your component hierarchy. As the creator of CoreUI with over 11 years of React development experience, I use custom hooks extensively to share common functionality like data fetching, form validation, and localStorage management across our UI components. Custom hooks are just JavaScript functions that start with “use” and can call other React hooks.
Import and call custom hooks at the top level of your React components, just like built-in hooks.
import { useLocalStorage } from './hooks/useLocalStorage'
import { useFetch } from './hooks/useFetch'
function UserProfile({ userId }) {
// Using custom hook for localStorage
const [theme, setTheme] = useLocalStorage('theme', 'light')
// Using custom hook for data fetching
const { data: user, loading, error } = useFetch(`/api/users/${userId}`)
if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
return (
<div className={`profile theme-${theme}`}>
<h1>{user?.name}</h1>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</div>
)
}
Custom hooks must follow the Rules of Hooks - call them only at the top level of React functions, not inside loops, conditions, or nested functions. They return values and functions that components need, often as arrays or objects. Multiple components can use the same custom hook independently - each gets its own isolated state. Custom hooks can call other hooks, including other custom hooks, making them composable and powerful for complex logic.
Best Practice Note:
In CoreUI components, we create custom hooks for theme management, responsive breakpoints, and form validation. This pattern keeps our components clean and focused on rendering while making complex functionality easily testable and reusable across our entire component library.



