
ReactJS
Custom Hooks let you extract component logic into reusable functions. They're JavaScript functions that use Hooks to share state logic.
Custom Hooks are functions that start with "use" and can call other Hooks. They let you extract component logic and reuse it across components.
import { useState, useEffect } from 'react';
// Custom Hook: useCounter
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
// Using the custom Hook
function Counter() {
const { count, increment, decrement } = useCounter(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
}Custom Hooks can wrap state logic, effects, or combine other Hooks. They make components cleaner and logic reusable.
// useLocalStorage: Persist state to localStorage
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
// Usage
function UserForm() {
const [name, setName] = useLocalStorage('name', '');
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your name"
/>
);
}| Element | Purpose |
|---|---|
| Custom Hook | Extract and share state logic |
| Naming | Start with "use" prefix |
| Returns | State, functions, or objects |
Ready to practice? Challenges
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward