Creating Custom Hooks in React
From the React Custom Hooks cheat sheet · Custom Hook Fundamentals · verified Jul 2026
Creating Custom Hooks
Master the art of creating reusable custom hooks for state management, side effects, and logic encapsulation
jsx
// Basic Custom Hook Pattern
import { useState, useEffect } from 'react'
// useCounter - Simple state management hook
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue)
const increment = () => setCount(prev => prev + 1)
const decrement = () => setCount(prev => prev - 1)
const reset = () => setCount(initialValue)
return { count, increment, decrement, reset }
}
// Using the hook
function Counter() {
const { count, increment, decrement, reset } = useCounter(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
)
}// Complete Counter Component
function CounterApp() {
const counter1 = useCounter(0)
const counter2 = useCounter(100)
return (
<div>
<div>
<h3>Counter 1: {counter1.count}</h3>
<button onClick={counter1.increment}>+</button>
<button onClick={counter1.decrement}>-</button>
<button onClick={counter1.reset}>Reset</button>
</div>
<div>
<h3>Counter 2: {counter2.count}</h3>
<button onClick={counter2.increment}>+</button>
<button onClick={counter2.decrement}>-</button>
<button onClick={counter2.reset}>Reset</button>
</div>
</div>
)
}🟢 Always prefix custom hooks with "use" to follow React conventions
💡 Custom hooks let you extract and reuse stateful logic between components
⚡ Return consistent data types from your hooks for predictable behavior
📌 Custom hooks can call other hooks, enabling powerful composition
⚠️ Follow the Rules of Hooks: only call at top level, not in conditions
state-managementreusabilitycompositionbest-practices