π Custom Hooks in React
A **Custom Hook** lets you extract and reuse logic between components. Itβs a regular function that uses built-in React hooks like useState
, useEffect
, etc.
π§ 1. Creating a Custom Hook
Custom hooks start with use
and can contain any reusable logic.
// useCounter.js
import { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
return { count, increment, decrement };
}
export default useCounter;
π¦ 2. Using the Custom Hook
Use it just like a built-in hook:
import useCounter from './useCounter';
function CounterComponent() {
const { count, increment, decrement } = useCounter(10);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
}
π‘ 3. Benefits of Custom Hooks
- Encapsulate logic and reuse it anywhere
- Keep components clean and readable
- Use other hooks inside them
π 4. Naming Rule
Always start with use
β e.g., useForm
, useAuth
, useDarkMode
. This ensures React treats it like a hook.
Custom hooks help organize logic across large apps by abstracting behavior into standalone, reusable functions.