Discover how a simple custom hook can save you hours of repetitive coding!
Why custom hooks are used in React - The Real Reasons
Imagine you have several React components that need to share the same logic, like fetching data or handling form inputs. You copy and paste the same code into each component.
Copying code everywhere makes your app hard to maintain. If you find a bug or want to improve the logic, you must update every place manually. This leads to mistakes and wasted time.
Custom hooks let you put shared logic into one place. Then, any component can use that logic by calling the custom hook. This keeps your code clean, reusable, and easy to update.
import { useState } from 'react'; function ComponentA() { const [count, setCount] = useState(0); // duplicated logic here } function ComponentB() { const [count, setCount] = useState(0); // duplicated logic here }
import { useState } from 'react'; function useCounter() { const [count, setCount] = useState(0); return { count, setCount }; } function ComponentA() { const { count, setCount } = useCounter(); } function ComponentB() { const { count, setCount } = useCounter(); }
Custom hooks enable easy sharing and reuse of logic across components, making your app simpler and faster to build.
Think of a shopping app where multiple pages need to track the user's cart state. A custom hook can manage the cart logic once, and all pages can use it without repeating code.
Copy-pasting logic causes bugs and hard maintenance.
Custom hooks let you share logic cleanly across components.
This leads to reusable, easier-to-update code.