0
0
Reactframework~3 mins

Why custom hooks are used in React - The Real Reasons

Choose your learning style9 modes available
The Big Idea

Discover how a simple custom hook can save you hours of repetitive coding!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
import { useState } from 'react';

function ComponentA() {
  const [count, setCount] = useState(0);
  // duplicated logic here
}

function ComponentB() {
  const [count, setCount] = useState(0);
  // duplicated logic here
}
After
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();
}
What It Enables

Custom hooks enable easy sharing and reuse of logic across components, making your app simpler and faster to build.

Real Life Example

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.

Key Takeaways

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.