Custom Hooks
-
This lesson introduces Custom Hooks and explains how to create reusable and maintainable logic using React Hooks.
Why Custom Hooks?
Custom Hooks help:
Reuse logic
Reduce duplication
Improve readability
Logic shared between components goes into custom hooks.
Creating Custom Hooks
Custom Hooks are normal functions starting with use.
Example:
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => setCount(c => c + 1);
return { count, increment };
}
Reusing Logic Across Components
Usage:
const { count, increment } = useCounter();
Same logic can be reused in multiple components.
Final Summary
useContext manages global data
useRef accesses DOM and stores values
useReducer handles complex state
useMemo and useCallback optimize performance
Custom Hooks promote reusability